YAML Anchors and Aliases Explained
One of YAML's most useful features is also one of its least understood: anchors and aliases let you define a block once and reuse it, keeping configuration DRY.
The problem they solve
Imagine three services that share the same logging config. Without reuse, you copy-paste it three times — and update it in three places forever. Anchors fix that.
Anchors (&) and aliases (*)
An anchor marks a node with &name. An alias references it with *name:
defaults: &defaults
retries: 3
timeout: 30
service_a:
<<: *defaults
name: a
service_b:
<<: *defaults
name: b
Both services inherit retries and timeout from the anchor.
Merge keys (<<)
The <<: *anchor syntax is a merge key — it merges the referenced mapping into the current one. You can override individual values after merging:
service_c:
<<: *defaults
timeout: 60 # overrides just this one
Anchoring scalars
Anchors aren't limited to mappings — you can anchor any node:
common_port: &port 8080
server:
port: *port
metrics:
port: *port
When to use them
- CI/CD pipelines with repeated job steps.
- Docker Compose services sharing environment blocks.
- Any config where the same values appear in multiple places.
Caveats
- Not all tools support merge keys — some parsers and some Kubernetes contexts ignore or reject
<<. Test before relying on it. - Readability can suffer if overused.
- Anchors are file-local — you can't reference one in another file.
Verify your YAML
Anchors and merge keys are easy to get subtly wrong. Paste your file into the validator to confirm it parses, and use the visualizer to see the resolved structure as a tree.
Got a config file to check?
Open the config toolkit →