YAML Tags
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 tagprefix
is a string that respect thetag:
URI scheme
For example:
%TAG ! tag:custom-uri
---
server: Linux-Server
datacenter:
location: new-york
zones: 12
points: 34
roles:
- backup
%TAG
is never used in practice.
Instead, everyone uses the two special tag handles:
- The primary tag handle is
!
, which by default expands to!
. So!bar
just resolves to!bar
, a local tag, specific to the document and not expected to be unique. - The secondary tag handle is
!!
, which by default expands totag:yaml.org,2002:
, the prefix YAML uses for its own built-in types. So!!bar
resolves totag:yaml.org,2002:bar
, and the tag for a string would more commonly be written as!!str
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
Local tags are not URIs, and they are not expected to be globally unique.
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
This can be done with any datatype. See other type in YAML Datatypes Chapter