Lesson 2 of 9 · 24m
YAML Architecture: includes, rules, and needs
Structure large pipeline files with includes, avoid rule explosions, and use needs to build an honest dependency graph.
The first CI file is usually twenty lines. The sixth iteration is nine hundred lines, five copies of the same deployment job, and a collection of when clauses nobody wants to touch. GitLab gives you better tools: includes for composition, rules for conditional creation, and needs for dependency order. Use them deliberately or they create a maze.
Includes are dependency management for CI
include:
- local: .gitlab/ci/test.yml
- local: .gitlab/ci/deploy.yml
- project: platform/ci-templates
ref: v2.4.0
file: security/container-scan.ymlPin remote templates to a version or commit. ref: main means your pipeline can change because somebody merged a template change at the wrong moment. Local includes are easier to review because the diff is in the same merge request.
rules decide whether a job exists
rules are evaluated top to bottom. The first matching rule wins. This is a job-creation mechanism, not a runtime if statement.
test:
script: bundle exec rspec
rules:
- if: '$CI_PIPELINE_SOURCE == "merge_request_event"'
- if: '$CI_COMMIT_BRANCH == "main"'
- when: neverThe failure mode is a rule matrix so clever that no one can predict which jobs appear. Keep conditions boring: merge request, default branch, tag, schedule. If the job needs more application-specific branching, put that logic in the script and log the decision.
needs turns stages into a DAG
build:
stage: build
script: make app
unit-test:
stage: test
needs: [build]
script: make unit-test
lint:
stage: test
needs: []
script: make lintHere lint does not wait for build, while unit-test starts as soon as build succeeds. That is a directed acyclic graph. It is the correct optimization when tests genuinely depend on artifacts, but a trap when used just to make the pipeline look busy.
Reference and inheritance
extends and YAML anchors reduce duplication, but deep inheritance hides behavior. Prefer one level of shared templates and explicit overrides for jobs that deploy, mutate infrastructure, or publish artifacts.
.base-test:
image: ruby:3.3
before_script:
- bundle install --jobs 4 --retry 3
unit-test:
extends: .base-test
script: bundle exec rspec spec/unitField notes
- Use
rulesfor job existence and script logic for application decisions. - A missing job usually means the rules excluded it, not that GitLab lost it.
needscan create cross-stage dependencies, but it cannot conjure artifacts that were never uploaded.- Pin external includes; floating refs are undeclared production dependencies.
- Large pipelines fail socially before technically: make ownership visible through file boundaries.
Was this lesson helpful?