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

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.

← Format your YAML now