Skip to main content
In this tutorial, you’ll learn how to leverage YAML anchors in GitLab CI/CD to DRY (Don’t Repeat Yourself) up your pipeline, creating reusable templates for deployment jobs. By defining anchors once and merging them across multiple jobs, you avoid boilerplate and simplify maintenance.

What Are YAML Anchors?

YAML anchors let you define a named block of configuration that can be duplicated or inherited later. In GitLab CI/CD, you typically combine anchors with hidden jobs (names starting with a dot) to build templates.
Hidden jobs are not executed directly. They serve as templates when you use the <<: merge key to inherit their configuration.

Basic Anchor Example

Merging Entire Job Configurations

You can reuse a full job template by defining it as a hidden job and then merging it into other jobs:
Here, test1 and test2 inherit image: ruby:2.6 and the two services from the hidden .job_template.

Combining Multiple Anchors

You can break a job template into smaller anchors—for example, separate anchors for script, services, or tags—and then merge only the pieces you need:
In this example, test_postgres inherits the base script and tags, then overrides services.

Real-World Pipeline: Reusing Deployment Configuration

Both k8s_dev_deploy and k8s_stage_deploy share:
  • alpine:3.7 as the job image
  • No dependencies
  • Identical before_script steps to install kubectl and gettext
Define a hidden job template with an anchor:

Dev Deploy Job

Stage Deploy Job

Now both deployment jobs inherit the same image, dependencies, and before_script steps without duplication.
The image shows a GitLab interface displaying the "Environments" section with active environments for "development" and "staging," including deployment details and options to open or stop them.

Visualizing the Pipeline

On the CI/CD > Pipelines page or the Visualization tab, confirm that:
  • k8s_dev_deploy runs immediately after docker_push thanks to needs:
  • k8s_stage_deploy is manual (when: manual)
  • Both jobs share the anchored configuration
The image shows a GitLab CI/CD pipeline interface for a NodeJS project, displaying stages like containerization, dev-deploy, and stage-deploy with their respective jobs.

Further Reading & References

That’s how you can use YAML anchors in GitLab CI/CD to keep your deployment jobs DRY and maintainable.

Watch Video