Skip to content

YAML Tags

Learn how to use YAML tags to define custom URIs, local tags, and specify data types with examples like ! for local tags and !! for built-in datatypes.

YAML Tags

YAML Tags are simple identifiers used to represent information about the type of native data structures.

YAML tags can be used in three ways:

  • to set a custom URI (universal resource indicator), which custom URI is used for reference.
  • to set local tags. The scope of local tag is only within the YAML file.
  • to set the data type of a variable.

Set a Custom URI (Universal Resource Indicator)

In YAML, custom URIs must be defined before the beginning of the document i.e. before the three dashes (---).

This can be done using the following syntax:

%TAG ! tag:prefix

where:

  • %TAG is a directive
  • ! starts the tag
  • prefix is a string that respect the tag: URI scheme

For example:

%TAG ! tag:custom-uri
---
server: Linux-Server
datacenter:
	location: new-york
	zones: 12
	points: 34
roles:
	- backup

Set a Local Tag

For declaring a local tag in YAML add the exclamation mark (!) and prefix to the value in the key-value pair.

name: ! local-tag-name value

For example:

%TAG ! tag:custom-uri
---
server: Linux-Server
datacenter:
	location: ! LOC new-york # local tag
	zones: 12
	points: 34
roles:
	- backup

Set Datatype using YAML Tag

You can also use a tag to change the reading functionality of the YAML parser in order to specify a datatype.

This is done by typing two exclamation marks !! followed by the name of the datatype.

For example, we want to specify the zip as a string:

house:
  road: "main road"
  city: "Big City"
  zip: !!str 12345
  floor: 4
Navigation