Module 2 Lesson 4: Advanced YAML in GitLab
·DevOps

Module 2 Lesson 4: Advanced YAML in GitLab

Master the nuances of YAML. Explore anchors, aliases, and multi-line strings to create cleaner, more maintainable pipeline configurations.

Module 2 Lesson 4: Advanced YAML in GitLab

YAML looks simple, but it has powerful features that allow you to follow the DRY (Don't Repeat Yourself) principle. This is essential when your pipeline grows to hundreds of lines.

1. YAML Anchors (&) and Aliases (*)

If you have 5 jobs that all use the same before_script, don't copy-paste it. Use an anchor.

.setup_template: &setup
  before_script:
    - apt-get update
    - npm install

job1:
  <<: *setup   # This "Stamps" the anchor here
  script:
    - npm test

job2:
  <<: *setup
  script:
    - npm run build

2. The !reference Keyword (GitLab Exclusive)

Traditional YAML anchors only work within the same file. To reuse partial code from other files or hidden jobs, GitLab created the !reference tag.

.scripts:
  test_logic:
    - echo "Running logic..."
    - ./test.sh

test_job:
  script:
    - !reference [.scripts, test_logic]
    - echo "Done!"

3. Multi-line Strings (> vs |)

  • | (Literal Block): Keeps your newlines. Use this for bash scripts.
  • > (Folded Block): Replaces newlines with spaces. Use this for long descriptions or secret keys.

4. Comments and Spacing

  • Use # for comments. Every line of a complex script should have a comment!
  • Always use spaces, never tabs. Tabs will cause a "Syntax Error" immediately.

Exercise: The DRY Challenge

  1. Look at Section 1. If you change the apt-get update command in the .setup_template, how many jobs will be affected?
  2. Write a multiline script using the | operator that prints 3 different lines of text.
  3. Why is the . prefix used in .setup_template? (Hint: See Module 2, Lesson 2).
  4. Research: What is the "YAML Merge Key" (<<)? Is it officially part of the latest YAML spec?

Summary

Advanced YAML features allow you to build pipelines that are "Smart." By using references and anchors, you ensure that a single change to your build logic propagates everywhere automatically, reducing bugs and saving time.

Next Lesson: Final verification: The Pipeline Editor and Linter.

Subscribe to our newsletter

Get the latest posts delivered right to your inbox.

Subscribe on LinkedIn