Introduction
As a YAML developer, many people are unaware of the Anchors feature in YAML. YAML Anchors allow you to define a piece of content in one place and reference it elsewhere in the file. This makes configuration files more concise, avoids repetitive work, and improves maintainability.
Usage
When defining a GitLab pipeline, for example, in a Spring Cloud project with many modules to compile, most parameters like the runner’s tag, stage, and trigger conditions are the same. However, some parameters, like environment variables, differ. In such cases, you can use YAML Anchors as follows:
# Define a default build configuration
default_build: &default_build
stage: build
when: manual
script:
- bash build.sh
tags:
- mvnd
# Use the default configuration and override specific variables
APP1-build:
<<: *default_build
variables:
APP_NAME: APP1
APP2-build:
<<: *default_build
variables:
APP_NAME: APP2
In the example above:
&default_build
defines an anchor containing a set of configurations shared by all jobs.<<: *default_build
merges this configuration into the APP1-build or APP2-build configurations.- If you need to override specific fields (e.g.,
script
orstage
), you can specify them in the respective environment configuration.
The above configuration is equivalent to:
APP1-build:
stage: build
when: manual
script:
- bash build.sh
tags:
- mvnd
variables:
APP_NAME: APP1
APP2-build:
stage: build
when: manual
script:
- bash build.sh
tags:
- mvnd
variables:
APP_NAME: APP2
Compared to the second configuration, the first one is much more concise. Additionally, if you need to modify the runner’s tag, you only need to change it in one place.
If the tags for APP1 and APP2 differ, you can write:
# Define a default build configuration
default_build: &default_build
stage: build
when: manual
script:
- bash build.sh
tags:
- mvnd
# Use the default configuration and override specific variables
APP1-build:
<<: *default_build
variables:
APP_NAME: APP1
APP2-build:
<<: *default_build
variables:
APP_NAME: APP2
tags:
- mvnd
- node
- mvn
In this case, under the tags
key, APP2 uses its own tags instead of the shared tags.
Notes
It is worth noting that not all parsers fully support Anchors and Aliases. For example, Docker Compose recommends using extension fields (e.g., x-xxx
) and overriding them in service configurations using *alias
instead of directly using merge keys.
x-common-env: &common_env
- DEBUG=true
- LOG_LEVEL=info
services:
app1:
environment: *common_env
image: myapp:latest
app2:
environment:
- DEBUG=false
- LOG_LEVEL=debug
- EXTRA_SETTING=app2
image: myapp:stable
In this case, x-common-env
is not treated as a service but is only used for reference.
Feel free to follow my blog at www.bboy.app
Have Fun