YAML Anchors and Aliases: Reuse Configuration Blocks

Learn how to use YAML anchors (&) and aliases (*) to avoid repeating configuration blocks. Understand merge keys (<<), override patterns, and how formatters handle anchor references.

YAML Features

Detailed Explanation

YAML Anchors and Aliases

YAML provides a built-in mechanism for reusing content within a document: anchors (&) define a reusable block, and aliases (*) reference that block elsewhere. This feature eliminates duplication in configuration files.

Basic Anchor and Alias

# Define an anchor
defaults: &default_settings
  timeout: 30
  retries: 3
  log_level: info

# Reuse with alias
production:
  <<: *default_settings
  log_level: warn

staging:
  <<: *default_settings
  timeout: 60

The &default_settings anchor marks the block for reuse. The *default_settings alias inserts a reference to that block. The << merge key merges the anchored mapping into the current mapping.

How Merge Works

When using <<: *alias, the aliased keys are merged into the current mapping. Local keys take precedence over merged keys:

# After resolution:
production:
  timeout: 30      # from anchor
  retries: 3       # from anchor
  log_level: warn  # overridden locally

Sequence Anchors

Anchors work with sequences (lists) too:

common_ports: &web_ports
  - 80
  - 443

service_a:
  ports: *web_ports

service_b:
  ports: *web_ports

Multiple Merges

You can merge multiple anchors into a single mapping:

base: &base
  timeout: 30

logging: &logging
  log_level: info
  log_format: json

service:
  <<: [*base, *logging]
  name: my-service

Formatter Considerations

When formatting YAML with anchors and aliases:

  • Anchor names should be preserved exactly as written
  • Indentation of anchored blocks must remain consistent
  • Order matters — an anchor must appear before any alias that references it
  • Some formatters offer an option to expand aliases (resolve them to their full content), which is useful for debugging but increases file size

Use Case

Anchors and aliases are widely used in Docker Compose files to share configuration between services, in CI/CD pipelines to reuse job templates, and in Ansible to share variables across playbooks. Understanding how formatters handle anchors ensures that shared configuration blocks remain correct after formatting.

Try It — YAML Formatter & Validator

Open full tool