Skip to content
Latchkey

How to Use YAML Anchors in a CircleCI Config

YAML anchors (&name) and aliases (*name) let you define a value or block once and reuse it verbatim, cutting repetition without any CircleCI-specific feature.

Anchor a reusable block with &name, then reference it with *name. Merge keys (<<: *name) splice an anchored map into another. This is plain YAML, so it works in both 2.0 and 2.1 configs.

Steps

  • Define a reusable mapping under a top-level key and mark it with an anchor &name.
  • Reference it elsewhere with *name, or splice it into a map with <<: *name.
  • Prefer 2.1 commands/executors for parameterized reuse; anchors are best for static blocks.

Config

.circleci/config.yml
version: 2.1
defaults: &node_docker
  docker:
    - image: cimg/node:20.11
jobs:
  lint:
    <<: *node_docker
    steps:
      - checkout
      - run: npm run lint
  test:
    <<: *node_docker
    steps:
      - checkout
      - run: npm test
workflows:
  ci:
    jobs: [lint, test]

Gotchas

  • Anchors must be defined before they are referenced in the file, top to bottom.
  • Anchors are static copies; when you need parameters or conditional logic, reach for commands and executors instead.

Related guides

Run this faster and cheaper on Latchkey managed runners. Start free →