YAML
Anchors and Aliases
If you have a common segment of yaml, you can create a reference to it. This is
known as an anchor in yaml terms. Anchors are represented with a &
character, similar to a C-style reference.
To use these anchors you can label a field as an alias, represented with an
* character. This is also similar to C-style pointer dereferencing. These
aliases will assuem the values of the anchored field.
If you would like to use an anchor as a template or base for your field and
want to change just a fiew fields. You can use value overrides by placing the
alias on it’s own line and prefixing it with <<: followed by a space. You can
then specify the fields to add or override on the next lines below this.
The << string denotes that the key-value pairs from another object or ‘map’
should be merged into the current map. Effectively taking the values from the
anchor and placing them in. This is what allows us to redefine the values, we
are redefineing these values. This is how overrides work in yaml with anchors.
See the following example of a pipeline configuration to see anchors, aliases, and overrides in use:
definitions:
steps:
- step: &build
name: Build step
script:
- make build
artifacts:
- bin/*.exe
- step: &deploy
name: Deployment step
deployment: dev, test
script:
- make deploy
pipelines:
branches:
feature:
- step: *build
- step: *deploy
develop:
- step: *build
- step:
<<: *deploy
deploymnt: test
release:
- step: *build
- step:
<<: *deploy
deployment: production
trigger: auth-required
Here is another example with a short grocery list:
groceries:
- &favorate Apple
- Bread
- Milk
- *favorate
This list will Shows that you can apply anchors to values as well as lists and objects.
Anchors as a whole can be redefined/overriden, it follows a top down approach, and must be defined before the use of an alias. Putting an alias before an anchor will caues an ‘reference does not exist’ error.