Feedback

Chat Icon

Cloud Native CI/CD with GitLab

From Commit to Production Ready

Consice, Reusable and Refactored Definitions
32%

YAML Anchors: Another Reusable Configuration Method

YAML anchors are another way to reuse sections of a YAML file. While extends is a GitLab-specific keyword, YAML anchors are a feature of the YAML syntax itself. This means that you can use YAML anchors in any YAML file, not just in GitLab CI/CD pipelines.

Before we dive into the details, let's see an example where the extends keyword fails. If you create the following pipeline:

cat <$HOME/todo/app/.gitlab-ci.yml
stages:
  - test

.base_test:
  - echo "Executing command 1..."
  - echo "Executing command 2..."
  - echo "Executing command 3..."

test:
  script:
    extends: .base_test
EOF

Then push the changes to GitLab:

cd $HOME/todo/app && \
git add . && \
git commit -m "Add concise pipelines" && \
git push origin main

You will get the following error in the pipeline:

jobs:test:script config should be a string or a nested array of strings up to 10 levels deep

The pipeline fails

The pipeline fails

The main reason for this error is that the extends keyword does not support YAML lists. To fix this issue, we can use YAML anchors. Anchors are a way to define reusable configuration sections. They work in an almost identical way to the extends keyword but there are some differences. Here is how we can can make use of anchors in general:

  • We create an anchor.
  • We give it an identifier/name (&identifier_of_the_anchor).
  • We reference the anchor in another block (<<: *identifier_of_the_anchor).

Cloud Native CI/CD with GitLab

From Commit to Production Ready

Enroll now to unlock all content and receive all future updates for free.