DevOps / GitLab CI Basics Interview Questions
What are YAML anchors and aliases in GitLab CI and how do they reduce duplication?
YAML anchors (&name) and aliases (*name) are standard YAML features that let you define a block once and reuse it multiple times. In GitLab CI, they reduce duplication for shared configuration like rules, before_script, or variables - without requiring the extends keyword.
# Define a reusable block with an anchor .common_rules: &common_rules rules: - if: $CI_COMMIT_BRANCH == "main" - if: $CI_PIPELINE_SOURCE == "merge_request_event" .common_setup: &common_setup image: node:20-alpine before_script: - npm ci # Reuse with alias (*) or merge key (<<: *) build-job: <<: *common_setup # merge the anchor content <<: *common_rules # YAML 1.1 syntax script: - npm run build test-job: <<: *common_setup <<: *common_rules script: - npm test # Anchors for variables .env_vars: &prod_vars variables: ENVIRONMENT: production LOG_LEVEL: error deploy-prod: <<: *prod_vars script: ./deploy.sh production
Anchors vs extends:
- YAML anchors are processed before GitLab reads the YAML - they are pure YAML features and work at the text level
- extends is a GitLab-specific feature processed after YAML parsing, offering deep merging, multiple parents, and better tooling visibility
- GitLab recommends using
extendsover YAML anchors for job configuration since it is more explicit and readable
More Related questions...