An anchor names a node, and an alias refers back to it. In YAML’s model the alias is the same node, not a copy, which is how a YAML file can describe shared or even circular data.
Anchors
An anchor is written as & followed by a name, in front of a node.
default: &base
retries: 3
timeout: 10
service:
settings: *base
settings is the same mapping as defaultA name can use any character that is not white space or a flow indicator
(, [ ] { }), and is
case-sensitive.
Aliases
An alias is written as * and the name. Its rules:
- It must refer to an anchor earlier in the same document. A reference to a later anchor, or one in another document, is an error.
- A name can be used again for another node. An alias refers to the most recent anchor of that name.
- An alias cannot have a tag or an anchor of its own.
- An alias is a whole node. It cannot be combined with text.
Merge keys
A merge key, <<, copies the keys of one or more mappings into the
current one. Keys already present in the mapping win over merged keys, and of several
merged mappings earlier ones win over later ones.
base: &base {a: 1, b: 2}
derived:
<<: *base
b: 9 # derived has a: 1 and b: 9
Merge keys come from the YAML 1.1 type repository (tag:yaml.org,2002:merge). They are not part of any YAML 1.2 schema, so a reader that supports them does so as an extension. Many readers do.
The value of a merge key can be an alias, a mapping, or a sequence of those.
Recursive structures
An alias inside the node that its anchor names makes a structure that contains itself. YAML allows this, because an alias points at the node, but not every reader can load it. JSON cannot represent it, so a converter must reject it or expand it.
&a [ *a ]
Alias expansion attacks
Aliases can multiply. A small file can name a list, repeat it in the next list, and so on, nine levels deep. A reader that copies each alias in place builds an enormous result; this is known as the billion laughs attack.
a: &a [x, x, x, x, x, x, x, x, x]
b: &b [*a, *a, *a, *a, *a, *a, *a, *a, *a]
c: &c [*b, *b, *b, *b, *b, *b, *b, *b, *b]
A reader should keep aliases as references, limit how many it follows, or refuse them altogether. The viewer on this site shows every alias as a link to its anchor and never copies it.
Specification
Anchors and aliases are in sections 3.2.2.2 and 7.1 of YAML 1.2.2. The merge key is on the YAML 1.1 merge type page.