YAML Anchors and Aliases

Anchors and aliases are YAML's way of reusing content. An anchor saves a block of YAML under a label. An alias references that saved block elsewhere in the same file. This removes the need to repeat identical content multiple times. The result is shorter, cleaner, and easier-to-maintain YAML files.

The Problem Anchors Solve

Consider a YAML configuration file for three different deployment environments: development, staging, and production. All three share many identical settings — database engine, timeout values, and logging format. Without anchors, the same settings must be written three times. Any future change requires updating all three copies — a maintenance headache.

Anchors let common settings be defined once and referenced as many times as needed.

Anchor Syntax

An anchor is created using the ampersand symbol & followed by a name. The name can be any word without spaces.

defaults: &default_settings
  timeout: 30
  retries: 3
  log_level: info

Here, &default_settings is the anchor. It names this block of three settings for reuse later.

Alias Syntax

An alias references a previously defined anchor using the asterisk symbol * followed by the anchor name.

production:
  <<: *default_settings
  log_level: error

The <<: *default_settings line pulls all settings from the anchor into the production mapping. The log_level line then overrides just that one value.

Anchor and Alias Diagram

+----------------------------+
|  Define Anchor             |
|  defaults: &default        |
|    timeout: 30             |
|    retries: 3              |
+----------------------------+
           ↓
           ↓  Referenced by Alias
           ↓
+----------------------------+
|  Use Alias                 |
|  production:               |
|    <<: *default            |
|    (inherits all above)    |
+----------------------------+

Full Example – Three Environments Sharing Common Settings

# Common settings defined once
common: &common
  database: postgres
  timeout: 30
  retries: 3
  cache: redis

# Development environment
development:
  <<: *common
  debug: true
  log_level: debug

# Staging environment
staging:
  <<: *common
  debug: false
  log_level: info

# Production environment
production:
  <<: *common
  debug: false
  log_level: error
  replicas: 3

All three environments inherit database, timeout, retries, and cache from the &common anchor. Each environment only defines its unique values. Changing timeout in one place updates all three environments automatically.

The Merge Key Operator (<<)

The << symbol is called the merge key. It is used alongside an alias to merge the anchor's key-value pairs into the current mapping. The merge key is a YAML 1.1 feature supported by most parsers.

base: &base
  color: blue
  size: medium

custom:
  <<: *base         # Merges color: blue and size: medium
  color: red        # Overrides only the color

After merging, custom has color: red and size: medium. The color key defined after the merge overrides the anchored value.

Override Priority Rule

When using merge keys, keys defined directly in the mapping take priority over keys brought in by the anchor.

+----------------------------------+
|  Anchor has:   color: blue       |
|  Direct key:   color: red        |
|                                  |
|  Result:       color: red        |
|  (Direct key wins over anchor)   |
+----------------------------------+

Anchoring a Scalar Value

Anchors work on individual scalar values too, not just mappings.

default_port: &port 8080

service_a:
  port: *port

service_b:
  port: *port

Both service_a and service_b use port 8080. Changing the anchor value updates both services at once.

Anchoring a List

common_packages: &packages
  - git
  - curl
  - vim

server_a:
  packages: *packages

server_b:
  packages: *packages

Both servers reference the same list of packages through the alias.

Real-World Example – GitHub Actions Reusing Job Settings

defaults: &job_defaults
  runs-on: ubuntu-latest
  timeout-minutes: 10

jobs:
  test:
    <<: *job_defaults
    steps:
      - run: npm test

  lint:
    <<: *job_defaults
    steps:
      - run: npm run lint

  build:
    <<: *job_defaults
    steps:
      - run: npm run build

Limitations of Anchors and Aliases

LimitationDetail
Same file onlyAnchors cannot reference content in another YAML file
No chaining logicAnchors cannot apply conditions or transforms
Parser support variesThe merge key << is not in the YAML 1.2 core spec but is widely supported
Readability riskToo many aliases make a file hard to follow without tracing each anchor

When to Use Anchors

  • When the same configuration block appears in multiple places in one file
  • When managing multiple environments (dev, staging, prod) with shared settings
  • When defining reusable defaults for CI/CD pipeline jobs
  • When a single value like a port number, version, or URL is used in many places

Summary

  • Anchors (&name) save a value or block for reuse
  • Aliases (*name) reference a previously defined anchor
  • The merge key (<<) merges anchor content into a mapping
  • Directly defined keys always override anchored keys
  • Anchors work on scalars, lists, and mappings
  • Anchors only work within the same YAML file

Leave a Comment