Consice, Reusable and Refactored Definitions
33%
Combining and Overriding YAML Blocks
Consider the following example where we have two identical blocks def_1 and def_2 and we want to combine them with another block (variables) in 2 different jobs. The first one will be used with a YAML anchor and the second one with GitLab's extends.
cat << EOF >$HOME/todo/app/.gitlab-ci.yml && \
git add .gitlab-ci.yml && \
git commit -m "experiment with anchors and extends" && \
git push origin main
.def_1: &def
variables:
VAR1: "value1"
VAR2: "value2"
.def_2:
variables:
VAR1: "value1"
VAR2: "value2"
job1:
<<: *def
variables:
VAR1: "new_value1"
script:
- 'echo "Job 1"'
- 'echo "VAR1: \$VAR1"'
- 'echo "VAR2: \$VAR2"'
job2:
extends: .def_2
variables:
VAR1: "new_value1"
script:
- 'echo "Job 2"'
- 'echo "VAR1: \$VAR1"'
- 'echo "VAR2: \$VAR2"'
EOF
ℹ️ The
<<operator is used to combine the content of the anchor with the content of the block.
This is how output of the first job (anchor) looks like. We can see that the variable VAR1 is overridden but VAR2 is removed. There is no combination at this point.
# VAR1 is overridden
VAR1: new_value1
# VAR2 is removed
VAR2:
Cloud Native CI/CD with GitLab
From Commit to Production ReadyEnroll now to unlock all content and receive all future updates for free.
