YAML & Config

YAML Anchors and Aliases Explained

An anchor names a YAML node and an alias refers to that node elsewhere in the same document. They can reduce repetition without creating cross-file variables.

Published

What an anchor and alias do

An anchor marks a node. An alias references that anchored node within the YAML document.

Anchor a mapping

defaults: &defaults
  retries: 3
  timeout: 5

Reuse it with an alias

The alias name is a reference, not an output key.

service:
  config: *defaults

Anchors with sequences and scalars

ports: &ports [8080, 9090]
workerPorts: *ports

Merge keys and parser behavior

The << merge-key convention is supported by some YAML toolchains but is not a core cross-version guarantee. Verify the target parser before relying on it; the interactive example uses a direct alias instead.

Common mistakes

  • Referencing an undefined alias.
  • Confusing the anchor name with a mapping key.
  • Breaking the surrounding structure with indentation.
  • Assuming an anchor can reference another file.

Readability trade-offs

Anchors reduce repeated data but add indirection. Prefer a little duplication when a distant alias would hide the effective configuration.

Try anchors in YAML Formatter

Load the parser-tested anchor and alias, then inspect the actual formatter behavior rather than assuming aliases will be expanded.

Try the example

Parse an anchor and alias

The service config refers to the defaults mapping in the same document.

defaults: &defaults
  retries: 3
  timeout: 5
service:
  config: *defaults

Expected result: Valid YAML with one anchor and one alias.

Test the syntax

Parse anchors and aliases

Run a small parser-tested example in YAML Formatter.

Open in YAML Formatter →