!reference) and standard YAML anchors to share configuration snippets across multiple jobs. By doing so, you can DRY up your pipeline definitions—pulling in values like image, before_script, or script from one job into another and avoiding duplication.
1. Basic YAML Anchors and !reference Tags
GitLab CI/CD supports two primary mechanisms for reusing snippets:
YAML anchors work within the same file, while
!reference can pull from hidden jobs or included files.2. Preparing the Kubernetes Environment
Let’s define two hidden jobs: one for Node.js and one for Kubernetes deployment. We’ll attach an anchor (&kubernetes_deploy_job) to reuse the Kubernetes job’s image later.
Make sure hidden jobs (prefixed with
.) are not executed on their own—they only serve as references.3. Two Almost-Identical Integration Tests
Consider two integration testing jobs—dev and staging. They share the sameimage, identical before_script, and script blocks:
!reference.
4. Reusing the image Definition
We can reuse the image from .prepare_deployment_environment with:
5. Reusing before_script and script Blocks
To avoid repeating before_script or script, reference the dev-integration job directly:
6. Full Snippet with Artifacts and Environment
For a consolidated pipeline, include artifacts and environment details alongside your reused blocks:Conclusion
By combining standard YAML anchors (& / *) with GitLab’s custom !reference tags, you can effectively DRY up your CI/CD definitions. Pull in common image, before_script, or script sections from hidden or existing jobs—simplifying maintenance and reducing errors.
Links and References
- GitLab CI/CD Reference Tags
- GitLab CI/CD Anchors and Aliases
- Kubernetes Official Documentation
- jq JSON Processor