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
Anchor and alias
defaults: &defaults
  retries: 3
  timeout: 30

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

# Define once and reuse many times.

Merge shared mappings
base: &base
  image: node:20
  pullPolicy: IfNotPresent

prod:
  <<: *base
  replicas: 3

# Combine a base config with environment-specific overrides.

Merge multiple anchors
common: &common
  logging: json
security: &security
  readOnlyRootFilesystem: true

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

# Compose config from several reusable blocks.

Expand anchors with yq
yq 'explode(.)' config.yaml

# Materialize merged values for inspection.

## Real-world reuse patterns
Reuse CI step fragments
steps: &install_steps
  - uses: actions/checkout@v4
  - run: npm ci

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

# Share common setup across jobs.

Reuse environment variables
env: &common_env
  NODE_ENV: production
  LOG_LEVEL: info

worker:
  env: *common_env

# Avoid copying the same environment block.

Catch duplicate mapping keys
yamllint config.yaml

# Lint for repeated keys that override silently in some parsers.

Recommended next

No recommendations yet.