Skip to content
Tutorials Center
My learning

Topics

Lesson 21 of 39 ยท YAML and Config Files

Anchors, Aliases, Tags and Documents in YAML

Reuse YAML data with anchors, aliases and merge keys, force types with tags, and keep several documents in one file - with runnable models of how each feature resolves.

Real configuration files repeat themselves: three services share the same restart policy, two environments share most of their settings. Copy and paste works until someone changes one copy and forgets the others. YAML has built-in reuse: anchors name a piece of data, aliases point back to it, and merge keys copy a whole mapping into another. This lesson also covers tags, which override how a value is typed, and documents, which let one file hold many YAML values.

The examples run in a Node sandbox with no YAML library. The TryIt blocks are stand-ins that model what a YAML loader does with these features, using ordinary JavaScript objects. Real loaders (yaml, js-yaml, PyYAML) implement the same rules.

Anchors and aliases

An anchor is a name attached to a node with &. An alias refers to that node with *. Wherever the alias appears, the loader inserts the anchored value.

YAML
defaults: &defaults
  restart: always
  log_level: info

api:
  settings: *defaults
worker:
  settings: *defaults

After loading, api.settings and worker.settings both hold {restart: always, log_level: info}. In many languages they are even the same object in memory, so changing one in code changes the other. Anchors must be defined before the alias that uses them, and the name is just letters, digits and dashes.

Anchors work on any node: a scalar (port: &p 8080, then *p), a list, or a mapping.

Merge keys: copy and override

An alias on its own reuses a whole value. Often you want to start from a base and change a few keys. The merge key << does that:

YAML
base: &base
  image: node:24
  restart: always
  env:
    mode: prod

web:
  <<: *base
  ports: ["8080:80"]
worker:
  <<: *base
  restart: "no"

web receives every key of base plus ports. worker receives the base keys but its own restart wins. You can merge several mappings with a list (<<: [*a, *b]); earlier ones win over later ones, and keys written directly in the mapping win over all merged ones.

The merge key is a YAML 1.1 feature. It is not part of the YAML 1.2 core schema, but most popular loaders (and tools such as Docker Compose) still support it. It is shallow: the nested env mapping above is shared, not deep-merged.

Node.js Model of anchors, aliases and merge keys

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

The shared env object is the usual surprise with merge keys. If you need independent copies, deep-copy after loading, or restructure the YAML so that the differing parts sit at the top level.

Tags: telling YAML the type

A tag is a label in front of a value that states its type, written !! for standard YAML types:

YAML
a: !!str 123        # the string "123", not a number
b: !!int "42"       # the number 42
c: !!float 1        # 1.0
d: !!binary |
  SGVsbG8=
e: !!set {red, green}

Tags are the precise alternative to quoting when you want to say "this is text". Application-specific tags start with a single ! (!Ref, !Sub, !include) and are how tools extend YAML: AWS CloudFormation uses !Ref and !GetAtt, and some config systems use !include to pull in another file. A generic loader does not know custom tags, so it must be configured with a handler or it will report an error.

Some YAML libraries can create arbitrary objects from tags such as !!python/object or !ruby/object. Never use that mode on untrusted input: it can execute code. See Data Format Security and always choose the "safe load" function.

Multiple documents in one file

A single YAML file can hold several independent values, called documents. Three dashes --- start a document and three dots ... optionally end one.

YAML
---
kind: Service
name: api
---
kind: Deployment
name: api
replicas: 3
...

Kubernetes manifests rely on this: kubectl apply -f app.yaml reads every document in the file. Loaders usually have two functions: one that expects exactly one document and one (loadAll, safe_load_all) that returns a list. A --- at the very top of a file is a document start marker and is harmless; the same line later splits the file.

You can also place a directive line before the first ---, such as %YAML 1.2, to state the version. It is rarely needed.

Node.js Splitting a multi-document stream

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Where reuse helps, and where it hurts

flowchart LR
  A["&defaults anchor"] --> B["*defaults alias (api)"]
  A --> C["*defaults alias (worker)"]
  A --> D["<<: merge + overrides"]

One definition, many uses.

Anchors keep files short, but they have costs. Readers must jump back to the anchor to know the real value. Many tools that process YAML as text (linters, some editors, GitHub Actions until it added limited support) do not resolve aliases. And a deeply aliased file can expand into a huge structure when loaded: the "billion laughs" attack applies to YAML too (see Data Format Security). Use anchors for a few clear shared blocks, not as a programming language.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Which pair defines an anchor and then uses it?

    An anchor is defined with an ampersand and referenced with an asterisk (the alias).
  2. 2. What does <<: *base do inside a mapping?

    The merge key inserts the key-value pairs of the aliased mapping. Keys written directly in the mapping override the merged ones.
  3. 3. What does id: !!str 007 produce?

    The !!str tag forces the string type, so the leading zeros are kept.
  4. 4. How do you put two documents in one YAML file?

    Three dashes on their own line start a new document. Kubernetes manifests commonly use this.
  5. 5. Why is merging with << called shallow?

    Only the top-level keys are copied; nested objects remain the same shared value, so they are not combined key by key.

Summary

  • &name defines an anchor, *name an alias; <<: *name merges a mapping and lets local keys override.
  • Merge is shallow and is a YAML 1.1 feature that most tools still support.
  • Tags (!!str, !!int, custom !Ref) override type resolution; avoid language-specific object tags on untrusted data.
  • --- separates documents; use a load-all function to read them.
  • Reuse sparingly: aliases hide values from readers and from text-based tools.

Next: YAML Gotchas and Pitfalls