YAML Anchors, Aliases, and Merge Keys

Reusable YAML patterns using anchors and aliases, with merge examples and commands for expanding and validating resolved config.

View
StandardDetailedCompact
Export
Copy the compact sheet, download it, or print it.
Download
`D` dense toggle · `C` copy all

Anchors and aliases

Reuse repeated YAML fragments without copy-paste.

Anchor and alias

Define once and reuse many times.

yamlANYyamlanchorsaliases
yaml
defaults: &defaults
  retries: 3
  timeout: 30

api:
  <<: *defaults
  url: https://api.example.com

Anchors reduce repetition and keep repeated config blocks synchronized.

Merge shared mappings

Combine a base config with environment-specific overrides.

yamlANYyamlmerge-keyreuse
yaml
base: &base
  image: node:20
  pullPolicy: IfNotPresent

prod:
  <<: *base
  replicas: 3

The merge key `<<` is widely used in tooling that supports YAML merge semantics.

Merge multiple anchors

Compose config from several reusable blocks.

yamlANYyamlanchorsmerge
yaml
common: &common
  logging: json
security: &security
  readOnlyRootFilesystem: true

service:
  <<: [*common, *security]
  port: 8080

Useful for DRY configuration where shared defaults come from multiple sources.

Expand anchors with yq

Materialize merged values for inspection.

bashANYyamlyqanchors
bash
yq 'explode(.)' config.yaml

Helpful when you want to see the fully resolved YAML after merges and aliases.

Real-world reuse patterns

Practical examples from CI, containers, and app config.

Reuse CI step fragments

Share common setup across jobs.

yamlANYyamlcireuse
yaml
steps: &install_steps
  - uses: actions/checkout@v4
  - run: npm ci

jobs:
  test:
    steps: *install_steps
  build:
    steps: *install_steps

A common pattern in CI configs when repeated steps would otherwise drift apart.

Reuse environment variables

Avoid copying the same environment block.

yamlANYyamlenvanchors
yaml
env: &common_env
  NODE_ENV: production
  LOG_LEVEL: info

worker:
  env: *common_env

Anchors make shared environment sections easier to maintain.

Catch duplicate mapping keys

Lint for repeated keys that override silently in some parsers.

bashANYyamlduplicate-keyslint
bash
yamllint config.yaml

Duplicate keys can hide anchor or merge mistakes, so linting is especially useful in large files.

Recommended next

No recommendations yet.