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/executorsfor 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
commandsandexecutorsinstead.
Related guides
How to Define Reusable Commands in CircleCIFactor repeated steps into a named CircleCI command with parameters, then call it across jobs to keep config…
How to Use pre-steps and post-steps in CircleCIInject setup and teardown around a reusable CircleCI job using pre-steps and post-steps when invoking it in a…