YAML Anchors and Aliases Explained
Anchors and aliases are the one part of YAML that looks genuinely unfamiliar the first time you see it, mostly because nothing else in the format uses punctuation quite like this. But the idea behind them is simple: don't repeat yourself.
The problem they solve
Say you have two environments that share almost identical settings:
staging:
timeout: 30
retries: 3
region: ap-south-1
production:
timeout: 30
retries: 3
region: ap-south-1
Copy-pasted blocks like this are exactly where config drift creeps in โ someone updates one and forgets the other.
Anchors and aliases fix the duplication
defaults: &defaults
timeout: 30
retries: 3
staging:
<<: *defaults
region: ap-south-1
production:
<<: *defaults
region: us-east-1
&defaults creates an anchor โ a labeled, reusable block. *defaults is an alias that says "insert everything from that anchor here." The <<: syntax is called a merge key, and it means "merge this anchor's keys into the current map," which lets staging and production each still add their own region on top.
What to watch out for
- Merge keys aren't supported everywhere. The
<<:merge syntax is common but technically comes from an older YAML spec draft, so double-check your specific parser or tool supports it before relying on it heavily. - Readability trade-off. Anchors save typing, but a file full of them is harder for a newcomer to trace โ they have to jump around to find what an alias actually expands to.
- Aliases copy structure, not intent. If you later need
stagingandproductionto diverge more than a couple of fields, an anchor-heavy setup can get awkward to unwind.
Anchors show up most often in Docker Compose files with repeated service settings, and in CI configs with repeated job steps. If you're not sure whether your specific parser expands them the way you expect, paste the file into our formatter and check the fully expanded output.