GitLab Hour 5: Production-Grade CI/CD — Reuse, Releases, and Orchestration

Upgrade the “one .gitlab-ci.yml per project” approach from the first four lessons to platform-style delivery: in mygroup-lab/platform publish versioned CI/CD components, orchestrate with parent-child and multi-project pipelines, manage artifacts with Releases, changelogs, and registry cleanup policies, reduce release risk with Review Apps, progressive rollout, and Feature Flags, then bring infrastructure into the same pipeline with GitLab-managed OpenTofu state
GitLab.com · GitLab 19.5glab v1.130.0CI/CD Catalog · spec:inputsMostly available on FreeMerge trains require PremiumVerified against official docs · 2026-11-16
Overall learning goals
  • Write a component project (templates/,spec:inputs type/default/options,spec:component context), use @$CI_COMMIT_SHA to self-test, use release keyword to publish semantic versions to CI/CD Catalog, and in myapp, reference it via @1.0.0 / @1 .
  • Use trigger:include (parent-child),trigger:project (multi-project),include:artifact (dynamic child pipelines) to orchestrate pipelines, and accurately predict strategy (without depend / mirror) how downstream status propagates upstream.
  • Retroactively create a Release for the lesson 2 v1.0 tag, use Git trailers and the changelog API to auto-generate release notes, and in tag pipelines use the release keyword (now implemented with glab) to publish v1.2.0.
  • Configure the container registry cleanup policies and protected container tags, publish generic and PyPI packages to the package registry, and explain why a given tag was deleted or kept.
  • Create a Review App for each MR (dynamic environment + on_stop + auto_stop_in), use manual or scheduled progressive rollout jobs to shift traffic in batches, and use GitLab Feature Flags (Unleash-compatible) to decouple “deploy” from “release”.
  • Understand the problems that merged results pipelines and merge trains (Premium) solve, and be able to approximate their effect on the Free tier with semi-linear or fast-forward merges plus “pipeline must succeed.”
  • Use the official OpenTofu CI/CD component with GitLab-managed state (HTTP backend, locking, versions) to run IaC pipelines, and complete the recap and cleanup of the first five lessons.

1-hour time allocation table

#TimeModuleCore contentAnimation / interactiveLab
0Before classPrep: multi-project sample groupIn mygroup-lab/platform create ci-components,deploy-config, and infra three projects; record their project IDsPrerequisite self-checkglab repo create,glab api
100–06CI/CD components and CI/CD Catalogcomponent directory structure,spec:inputs types and validation,spec:component, self-test, semantic-version release, Catalog visibilitycomponent input parser (including 6 failure scenarios)Publish python-test@1.0.0 and use it in myapp
206–13Parent-child and multi-project pipelinestrigger:include / project / forward / inputs, dynamic child pipelines,strategy: depend vs mirror, nesting, and permission restrictionsCore animation: upstream and downstream status propagationparent-child + dynamic child pipeline + trigger deploy-config
313–21Releases, tags, and changelogsRelease object,release keyword (glab),glab release create, Changelog trailers and API, asset links, permanent links, deployment freezesTag → release pipeline, step-by-step replayBackfill a Release for v1.0; publish v1.2.0
421–28Packages and container registryCI_REGISTRY_IMAGE, evaluation order of cleanup policies, protected and immutable container tags, generic and PyPI packages, package cleanup policiescleanup policy evaluatorConfigure a cleanup policy + publish a generic package
528–35Deployment strategies: progressive rollout, Feature Flags, and Review Appsdynamic environments,on_stop,auto_stop_in; manual or scheduled progressive rollout; Unleash-compatible Feature Flags and strategiestraffic percentage × flag percentage simulatorMR Review App lifecycle + 25% Feature Flag
635–42Merge trains and merged results pipelinesmerged results commits, train queuing and restart, concurrency limit of 20; Free alternative: semi-linear or fast-forward mergesmerge train simulator (re-ordering after B fails)Free: semi-linear merge walkthrough; Premium: enable trains
742–50Infrastructure as code: GitLab-managed Terraform stateOpenTofu component 5.1.0, HTTP backend and locking,glab opentofu, the plan report in MRs, plan file securityState locking and versioning (two pipelines competing)Zero-cost tofu project: plan → apply → lock conflict → version history review
850–60Recap of the first five hours, self-test, and cleanupKnowledge map for the five lessons, readiness check, cleanup in dependency order, interactive troubleshooting treeKnowledge map + troubleshooting treeCleanup script
—After classCheat sheet · Capstone labComponents → parent-child orchestration → v1.2.0 release → cleanup policies → Feature Flag → IaC stateFinal quiz (12 questions)Capstone lab

Knowledge Coverage Matrix

Target skillsM1M2M3M4M5M6M7M8Key commands / keywordsLab
Write, test, and release a CI/CD component✓✓✓···✓✓spec:inputs,include:component,releaseM1
Parent-child / multi-project / dynamic child pipeline orchestration·✓··✓·✓✓trigger,strategy: mirror,include:artifactM2
Predict upstream and downstream status propagation·✓···✓·✓strategy: depend / mirrorM2 animation
Releases, changelogs, assets✓·✓✓···✓glab release create,/repository/changelogM3
Container and package registry and storage governance··✓✓···✓container_expiration_policy_attributes,packages/genericM4
Review Apps and dynamic environments····✓✓·✓environment:on_stop,auto_stop_inM5
Progressive rollout and Feature Flags····✓···when: delayed,/feature_flags, UnleashM5
Merged results pipeline / merge trains / Free alternative·····✓·✓merge_trains_enabled,merge_methodM6
GitLab-managed OpenTofu state✓✓····✓✓backend "http",glab opentofuM7

What this lesson does not cover (and where to learn it)

TopicWhy it is not in this lessonWhere to learn
HCL syntax, providers, module design,terraform test, state internalsThis lesson only covers how GitLab stores state and how to run IaC in pipelinesTerraform 8-hour course
include merge rules,rules,needs Basics and referencing official componentsCovered in lesson 2; this lesson continues from “writing components and publishing components”Lesson 2 (Module 7)
Identity chain for deploying to Azure / AWS (OIDC)Covered in lessons 3 and 4; this lesson's deployment examples reuse the variables from thereLesson 3 · Lesson 4
Security scanning, SBOM, signing, pipeline execution policiesBelongs to the “DevSecOps and supply chain” topicLesson 6
Canary on Kubernetes (Ingress weights, Argo Rollouts)Belongs to Kubernetes platform capabilities; this lesson only covers GitLab-side orchestrationKubernetes course
How the same topic is written in GitHub Actions / Azure Pipelines / JenkinsThis lesson covers GitLab onlyGitHub · Azure DevOps · Jenkins

How to use this courseware

10 pages per module
Principles · diagrams · animations · commands · labs · production cases · troubleshooting · quizzes · audio · video. The “component input parsing” in Module 1 and the “status propagation” in Module 2 are the two core animations of the course; watch the animation before doing the lab.
Learning progress
A quiz score ≥ 70% or clicking “Mark module complete” counts toward progress; it is saved in this browser (cleared on refresh if local storage is disabled).
Chinese audio
The “Audio” page uses the browser's Web Speech API (en-US) to read the lecture script aloud; without a Chinese voice pack, the script is still readable.
Costs, tiers, and security notes Except for the merge trains in Module 6 (Premium / Ultimate, available with a GitLab trial), this lesson can be completed on the Free tier, and by default creates no cloud resources: the Module 5 Review App / progressive rollout lab only rehearses the GitLab-side environment lifecycle; cloud deployment is an optional snippet (reusing the Container Apps from lesson 3, which you must rebuild yourself and which incurs a small cost); the Module 7 OpenTofu lab only uses random / terraform_data, at zero cost. GitLab.com Free provides 400 compute minutes per month per top-level namespace (verified in lesson 2), and the whole lesson uses about 20–40 minutes; use the self-hosted runner from lesson 2 (tag lab-docker) does not consume compute minutes. The three new projects are also subject to the Free tier storage quota, which is exactly why Module 4 configures cleanup policies.
Version notes (verified 2026-11-16) GitLab.com runs GitLab 19.x (latest released: 19.5, patch 19.5.6; 19.6 not yet released). Components and the CI/CD Catalog are available 17.0 GA on the Free tier; each component project supports up to 100 components (since 18.5); spec:component context GA in 18.7. trigger:strategy: mirror Since 18.2 was introduced, official docs now label depend as “not recommended.”release Since 18.0, the keyword switched to glab (GA in 18.4),release-cli is deprecated and planned for removal in 20.0. Protected container tags went GA in 17.11 (Free), and immutable container tags in 18.10 (Ultimate). GitLab's Terraform CI/CD templates were removed in 18.0, and the official recommendation is gitlab.com/components/opentofu (current 5.1.0, 2026-11-06, default OpenTofu 1.13.9).

Module 0 · Prep: multi-project sample group (complete before class)

In the subgroup created in lesson 1 mygroup-lab/platform create three new projects as the “platform team” component library, deployment configuration repository, and infrastructure repository
Before class ≈ 10 minFreeglab · git · python3
Prerequisites
  • Completelesson 2: mygroup-lab/myapp 's .gitlab-ci.yml (stages lint / test / build / verify,python-lint,unit-test matrix,integration-test,build-image,smoke) merged, the tag v1.0 published, image registry.gitlab.com/mygroup-lab/myapp:1.0 exists.
  • Cloud resources from lessons 3 and 4 may already be cleaned up; this lesson does not depend on them. Lesson 3's v1.1 tag, if it exists, will be treated as the previous version in this lesson's release notes.
  • In mygroup-lab you are Owner (publishing to the Catalog requires the Owner role on the component project),glab auth status that is normal; this machine has git,python3,jq, and Module 7 requires OpenTofu(optional, built into CI).

How this connects to the first four lessons

Already exists (lessons 1–4)How this lesson uses it
group mygroup-lab (private, 2FA enforced) and the subgroup platformAll three new projects go under platform ; members and permissions are inherited automatically
main Protected (push: No one), tags * are protected (Maintainer)myapp's v1.2.0 releases can still only be created by Maintainers; new projects follow the same rule
Lesson 2 .gitlab-ci.yml (python-lint,unit-test)Module 1 replaces these two jobs with a component; the job names change to ruff,pytest
Lesson 2 build-image: main push short-SHA tags,v* tag pushes ${CI_COMMIT_TAG#v}Module 4's cleanup policy is designed around this: “keep version numbers, expire short SHAs”
Lesson 3 Container Apps (myapp-dev / myapp-prod, revision weights)The optional cloud snippet in Module 5 uses the same az containerapp ingress traffic set syntax
self-hosted runner gitlab-runner (tag lab-docker)Jobs that need DinD continue to use it, saving compute minutes

Step 1: set environment variables

export GL_USER=$(glab api user | jq -r .username)
export GL_GROUP=mygroup-lab                       # replace with <your-username>-lab
export GL_PROJECT=$GL_GROUP/myapp
export COMP_PROJECT=$GL_GROUP/platform/ci-components
export DEPLOY_PROJECT=$GL_GROUP/platform/deploy-config
export INFRA_PROJECT=$GL_GROUP/platform/infra
enc() { printf %s "$1" | jq -sRr @uri; }          # path → URL encoding, for use with glab api
cat > ~/gitlablab/part5.env <<EOF
export GL_USER=$GL_USER GL_GROUP=$GL_GROUP GL_PROJECT=$GL_PROJECT
export COMP_PROJECT=$COMP_PROJECT DEPLOY_PROJECT=$DEPLOY_PROJECT INFRA_PROJECT=$INFRA_PROJECT
EOF

Step 2: create three projects

for p in ci-components deploy-config infra; do
  mkdir -p ~/gitlablab/$p && cd ~/gitlablab/$p
  glab repo create "$GL_GROUP/platform/$p" --private --defaultBranch main \
    -d "platform: $p (GitLab lesson 5)"
done
cd ~/gitlablab
for p in "$COMP_PROJECT" "$DEPLOY_PROJECT" "$INFRA_PROJECT"; do
  glab api "projects/$(enc "$p")" | jq -c '{path_with_namespace, id, visibility, default_branch}'
done
✓ Created repository mygroup-lab/platform/ci-components on GitLab: https://gitlab.com/mygroup-lab/platform/ci-components
✓ Added remote git@gitlab.com:mygroup-lab/platform/ci-components.git
…
{"path_with_namespace":"mygroup-lab/platform/ci-components","id":71000001,"visibility":"private","default_branch":"main"}
{"path_with_namespace":"mygroup-lab/platform/deploy-config","id":71000002,"visibility":"private","default_branch":"main"}
{"path_with_namespace":"mygroup-lab/platform/infra","id":71000003,"visibility":"private","default_branch":"main"}

glab repo create Initialize Git in the current directory and add origin (this does not push any commits). The project description must not be omitted: component projects without a description cannot be published to the Catalog. Project IDs shown are example values.

Step 3: add the same protection to component projects as myapp

CP=$(enc "$COMP_PROJECT")
# Tags: Maintainer only (publishing a version = creating a tag)
glab api -X POST "projects/$CP/protected_tags" -f name='*' -f create_access_level=40
# Default branch: direct pushes forbidden; merge only via MR (best practice for component maintainers; official docs “For component maintainers”)
glab api -X POST "projects/$CP/protected_branches" -f name=main -f push_access_level=0 -f merge_access_level=40 2>/dev/null \
  || echo "main is already protected by the group's default rules"
A small pitfall before the first push If the group's “default branch protection” has already set the new project's main to “Not allowed to push,” the first git push -u origin main will be rejected. In the lab, you can push first and then run the protection commands above, or leave the initial push permission to Maintainers in the group settings.

Warm-up: answer from memory (30 seconds)

include:project and include:component both can reuse YAML across projects. What does the latter add?

Interface (spec:inputs: types, defaults, allowed values, regex validation), version semantics (tag / SHA / partial semver 1,~latest), discoverability and documentation (CI/CD Catalog, README), and component context ($[[ component.version ]]). include:project only “merges that ref of that file in”; variables are not validated, and a typo just becomes an empty string.

In lesson 2, the v1.0 tag pipeline pushed image :1.0, does the project's “Releases” page have it?

No. A Git tag is only a reference to a commit; Release is an object GitLab adds on top of tags (release notes, asset links, milestones, evidence). Module 3 uses glab release create v1.0 to backfill Releases for existing tags.

Does the job that triggers a child pipeline need a runner?

No. trigger job (bridge job) is handled by GitLab itself: it resolves the downstream configuration and creates the downstream pipeline. So if it runs for a long time pending usually means the downstream pipeline could not be created (permissions, a configuration error, or rules that leave the downstream empty).

Environment self-check checklist

Module 1 · CI/CD components and CI/CD Catalog

00:00 – 06:00 · Turn copy-pasted YAML into a component with an “interface, version, and docs”
6 minGA 17.0 · Freespec:component 18.7 GA★★★★★
Learning goals
  • Write a compliant component project: templates/<name>.yml or templates/<name>/template.yml, a root directory README.md, and do not use global keywords.
  • Be proficient with spec:inputs of the type (string / number / boolean / array),default,options,regex,description, and spec:component: [name, version, sha, reference].
  • Choose a version by the rule “commit SHA > tag > branch > ~latest / partial version”; understand that partial versions only apply to versions already published in the Catalog.
  • Use @$CI_COMMIT_SHA to self-test the component, use release keyword to publish semantic versions, so the project appears in the CI/CD Catalog.
Prerequisites: Lesson 2, Module 7 (include merge rules, referencing official components). Importance:★★★★★

What: a component = a versioned YAML unit + an input interface

A component project is an ordinary GitLab project, organized by convention. Each component is a YAML file under templates/ (or the template.yml file in a directory), with the file header's spec block declaring the interface,--- followed by job definitions. Consumers use include:component to reference it, in this fixed format:

<instance FQDN>/<full project path>/<component name>@<version>
gitlab.com/mygroup-lab/platform/ci-components/python-test@1.0.0
$CI_SERVER_FQDN/mygroup-lab/platform/ci-components/python-test@1.0.0   ← recommended; avoid hardcoding the hostname
Constraints (official docs)Description
Directory structureRoot directory README.md + templates/; in directory form, only template.yml is published to consumers, while test scripts and Dockerfiles in the same directory are not
LimitEach project allows at most 100 components (from 18.5, previously 30); components that need an independent release cadence should go in separate projects
Same instancecan only reference components on the same GitLab instance; self-managed instances that want to use GitLab.com components need to mirror that project (Premium / Ultimate)
AccessPrivate component projects: consumers need the Reporter role or higher on the component project (inherited from group membership is sufficient)
spec Available keywordsdescription,inputs,component; within a component,cannot use spec:include

Why: why upgrade from include:project or templates

  • The interface is validated: missing required inputs, wrong types, values not in options the list, values that do not match regex, or undeclared inputs passed; all of these are reported at pipeline creation time; whereas a misspelled CI/CD variable silently becomes an empty string.
  • Version control: consumers decide when to upgrade; authors can release 2.0.0 without immediately breaking @1 existing consumers.
  • Discoverable: the Catalog shows the description, README, each component's input table, the version list, and the number of projects that used it in the last 30 days.

How: when inputs are resolved

Inputs are evaluated at pipeline creation or when the configuration is fetched (before variable expansion and before rules): GitLab fetches the component file → uses spec:inputs to validate include:inputs → interpolates $[[ inputs.x ]] by type (keeps the type when replacing a whole value, always converts to a string when embedded in a larger string) → merges the result into the pipeline configuration per include merge rules → then does variable and rules evaluation. Limits: a single interpolation block must be < 1 KB, and strings using interpolation must be < 1 MB; up to 3 functions can be chained in one interpolation block (e.g., expand_vars,truncate,posix_escape).

Version selection rules

SyntaxMeaningSuitable for
@e3262fdd… (full SHA)Highest priority; SHA takes precedence over a tag with the same nameProduction pipelines with the highest security requirements (recommended by official docs)
@1.0.0 (tag)Catalog publishing must use semantic versionsGeneral production use
@main (branch)Tags take precedence over branches with the same nameOnly for testing
@1 / @1.2 / @~latestLatest matching version published in the Catalog; pre-release versions are never selected (e.g., 1.0.1-rc); only applies to Catalog projectsWhen you are willing to automatically receive patch and minor updates

Official example: with published versions 1.0.0, 1.1.0, 1.1.1, 1.2.0, 2.0.0, 2.0.1, 2.1.0,@1 → 1.2.0,@1.1 → 1.1.1,@~latest → 2.1.0.

When: when to write a component

  • The same YAML copied into 3 or more projects → component.
  • Splitting only within one repo → include:local is enough.
  • When a whole sub-process (such as OpenTofu's validate/plan/apply) needs to be handed to consumers → component + (optional) trigger:include:component as a child pipeline (Modules 2, 7).

Comparison with similar technologies

GitLab componentsGitHub reusable workflows / ActionsAzure Pipelines templatesJenkins shared libraries
Interfacespec:inputs (types, options, regex)inputs (types, required)parameters (types, values)Groovy function parameters
VersionSHA / tag / branch / partial semverSHA / tag / branchresources.repositories ref@Library('x@1.0')
DiscoveryCI/CD CatalogMarketplaceNo unified directoryNo unified directory
Seethis lessonGitHub courseAzure DevOps courseJenkins course
Common misconceptions① “Components run independently” — no; component content is merged into your pipeline; jobs with the same name are merged into one, and same-named hidden jobs can be overridden by your extends misuse. ② “@~latest can pull the latest commit on main” — it only matches versions in the Catalog that have been published versions; if nothing has been published, it fails with content not found③ “Creating a Release via the Releases API also publishes it to the Catalog” — no; it must be done with the CI job's release keyword. ④ “Writing stages: is convenient” — global keywords affect the consumer's entire pipeline, so official docs recommend avoiding them.

Component project structure and publishing path

mygroup-lab/platform/ci-components ├── README.md ← required (Catalog page) ├── LICENSE.md ├── templates/ │ ├── python-test/ │ │ ├── template.yml ← component python-test │ │ └── README.md (not published to consumers with the version) │ └── docker-build.yml ← component docker-build ├── fixtures/sample/ ← sample app for self-testing └── .gitlab-ci.yml ← self-test + publish Project description required · tags must be semantic versions ① MR pipeline self-testcomponent …@$CI_COMMIT_SHA ② Create tag 1.0.0Tag pipeline: test → release job ③ release keywordglab release create (CI_JOB_TOKEN) CI/CD Catalog Enable “CI/CD Catalog project” (Owner required)Versions: 1.0.0 · 1.1.0 · …Visibility = source project visibilityPrivate: visible to members; usable by Reporter+ Consumer mygroup-lab/myapp include:- component: …/python-test@1 inputs: { coverage_min: 70 }
Figure 1-1 Component project: the same repo is both the component source and its own test and release pipeline

Input parsing flow (when a pipeline is created)

Resolve versionSHA › tag › branch› @1 / ~latest Read component filetemplates/x.yml ortemplates/x/template.yml Validate inputsUnknown keys · required · typeoptions · regex Interpolate$[[ inputs.x ]]$[[ component.version ]] Merge into pipelinethen expand variables,rules evaluation If any step fails, the pipeline is not created (or is created as failed and shows a YAML error); no job starts running
Figure 1-2 Inputs are parsed in the “fetch configuration” stage, so they are earlier and stricter than CI/CD variables

Core animation: component input parsing (include:component → validate → interpolate → merge)

Pick a scenario, then click “Next” or “Autoplay.” The left side is myapp's include, the right side is the component's spec:inputs; the terminal below shows GitLab's real processing and errors when creating the pipeline (see the sources page for the error wording).

Select a scenario to start.
$ # pipeline creation log

Common commands and keywords

Command / keywordPurposeKey parameters / notes
include: - component: $CI_SERVER_FQDN/<path>/<name>@<version>Reference a componentinputs: pass inputs; rules can be included conditionally
spec: inputs: x: {type, default, options, regex, description}Declare the interfaceNone default i.e., required; type defaults to string
spec: component: [name, version, sha, reference]Declare the component context neededUse $[[ component.version ]] to reference (18.7 GA)
glab ci lintLocal validation .gitlab-ci.ymlincludes component parsing and input validation
glab api graphql -f query='mutation{catalogResourcesCreate(…)}'Turn a project into a Catalog projectEquivalent to the UI toggle; requires Owner; this GraphQL change is marked Experiment
glab release list -R <component project>List published versionsCorresponds to the Catalog's version list
glab ci config compileView the full merged configurationVerify component interpolation results (using glab ci --help as the reference)

Component 1: templates/python-test/template.yml

spec:
  description: "ruff check + pytest matrix tests (with coverage threshold), for reuse by Python services"
  component: [name, version]
  inputs:
    stage:
      default: test
      description: "Stage where the pytest job runs"
    lint_stage:
      default: lint
      description: "Stage where the ruff job runs"
    python_versions:
      type: array
      default: ["3.12", "3.13"]
      description: "Python version in the test matrix"
    root_dir:
      default: "."
      description: "Project root directory (containing requirements*.txt)"
    coverage_min:
      type: number
      default: 80
      description: "Fail when coverage is below this value"
    lint:
      type: boolean
      default: true
    report_format:
      default: cobertura
      options: ["cobertura", "jacoco"]
---
ruff:
  stage: $[[ inputs.lint_stage ]]
  image: python:3.13-slim
  rules:
    - if: '"$[[ inputs.lint ]]" == "true"'
  script:
    - cd "$[[ inputs.root_dir ]]"
    - pip install -q ruff
    - ruff check .

pytest:
  stage: $[[ inputs.stage ]]
  image: python:${PY}-slim
  parallel:
    matrix:
      - PY: $[[ inputs.python_versions ]]
  variables:
    PIP_CACHE_DIR: $CI_PROJECT_DIR/.cache/pip
  cache:
    key: pip-$PY
    paths: [.cache/pip]
  script:
    - echo "using $[[ component.name ]]@$[[ component.version ]]"
    - cd "$[[ inputs.root_dir ]]"
    - pip install -q -r requirements.txt -r requirements-dev.txt
    - pytest -q --junitxml=report.xml --cov --cov-report=term --cov-report=xml --cov-fail-under=$[[ inputs.coverage_min ]]
  coverage: '/TOTAL.*? (\d+(?:\.\d+)?)%/'
  artifacts:
    when: always
    reports:
      junit: $[[ inputs.root_dir ]]/report.xml
      coverage_report:
        coverage_format: $[[ inputs.report_format ]]
        path: $[[ inputs.root_dir ]]/coverage.xml

Key points:① PY: $[[ inputs.python_versions ]] is a “whole-value replacement”; arrays are inserted as arrays, which is why the matrix works. ② Within rules:if interpolation, the expression must remain valid, so the input and the whole expression are quoted (official troubleshooting advice). ③ There is no stages:,default:,workflow: , etc. global keywords. ④ The job name ruff / pytest will collide with a same-named job in the consumer project merged— consumers can use this to override tags and so on, but avoid accidental name collisions.

Component 2: templates/docker-build.yml

spec:
  description: "DinD image build; main pushes the short SHA, v* tags push the version number without the v"
  component: [version]
  inputs:
    stage:
      default: build
    image:
      default: $CI_REGISTRY_IMAGE
    context:
      default: "."
    push:
      type: boolean
      default: true
    docker_version:
      default: "29"
      regex: ^\d+(\.\d+)*$
---
docker-build:
  stage: $[[ inputs.stage ]]
  image: docker:$[[ inputs.docker_version ]]
  services: ["docker:$[[ inputs.docker_version ]]-dind"]
  variables:
    DOCKER_TLS_CERTDIR: "/certs"
    IMAGE: $[[ inputs.image ]]:$CI_COMMIT_SHORT_SHA
  script:
    - docker build --pull --label "org.opencontainers.image.revision=$CI_COMMIT_SHA" --label "built-by=docker-build@$[[ component.version ]]" -t "$IMAGE" "$[[ inputs.context ]]"
    - |
      if [ "$[[ inputs.push ]]" = "true" ] && [ "$CI_PIPELINE_SOURCE" != "merge_request_event" ]; then
        echo "$CI_REGISTRY_PASSWORD" | docker login "$CI_REGISTRY" -u "$CI_REGISTRY_USER" --password-stdin
        docker push "$IMAGE"
        if [ -n "$CI_COMMIT_TAG" ]; then
          docker tag "$IMAGE" "$[[ inputs.image ]]:${CI_COMMIT_TAG#v}"
          docker push "$[[ inputs.image ]]:${CI_COMMIT_TAG#v}"
        fi
      fi

$[[ inputs.image ]] 's default value $CI_REGISTRY_IMAGE remains a variable reference after interpolation and is only expanded at job runtime to the consumer project's repository address. This is exactly the “inputs before variables” principle at work. regex Prevents someone from passing latest and similar floating tags.

How to verify · common errors · production use

  • Verify:glab ci lint; or view the interpolated result in the “Full configuration” tab of the pipeline editor.
  • Common errors: the component file has jobs but forgot to write ---; spec:inputs is empty, causing the release to report Spec must be a valid json schema (if no inputs are needed, write an empty spec:).
  • Production use: The platform team maintains 3–10 components (testing, build, scanning, deployment), and application projects need only a dozen or so lines of include.

Lab 1: publish python-test@1.0.0 and use it in myapp (about 15 min)

1. Write the component and a self-test sample (in ~/gitlablab/ci-components)
cd ~/gitlablab/ci-components
mkdir -p templates/python-test fixtures/sample/tests
# Save the two component files from the “Commands” tab as templates/python-test/template.yml and templates/docker-build.yml, respectively
cat > fixtures/sample/app.py <<'EOF'
def add(a, b):
    return a + b
EOF
cat > fixtures/sample/tests/test_app.py <<'EOF'
from app import add

def test_add():
    assert add(2, 3) == 5
EOF
printf 'pytest\npytest-cov\n' > fixtures/sample/requirements-dev.txt
: > fixtures/sample/requirements.txt
printf '[tool.pytest.ini_options]\npythonpath = ["."]\n[tool.coverage.run]\nsource = ["."]\n' > fixtures/sample/pyproject.toml
2. README and the component project's own pipeline
cat > README.md <<'EOF'
# ci-components
CI/CD components maintained by the mygroup-lab platform team.

| Component | Purpose | Key inputs |
|------|------|----------|
| python-test | ruff + pytest matrix + coverage threshold | python_versions, coverage_min, lint |
| docker-build | DinD build and push image | image, push, docker_version |

```yaml
include:
  - component: $CI_SERVER_FQDN/mygroup-lab/platform/ci-components/python-test@1.0.0
    inputs:
      coverage_min: 70
```
EOF
cat > .gitlab-ci.yml <<'EOF'
stages: [lint, test, build, release]

include:
  # Self-test the component with the current commit: set the version to $CI_COMMIT_SHA
  - component: $CI_SERVER_FQDN/$CI_PROJECT_PATH/python-test@$CI_COMMIT_SHA
    inputs:
      root_dir: fixtures/sample
      python_versions: ["3.13"]
      coverage_min: 90
  - component: $CI_SERVER_FQDN/$CI_PROJECT_PATH/docker-build@$CI_COMMIT_SHA
    inputs:
      push: false
      context: fixtures/sample

# The docker-build component has no Dockerfile to build → override script here to only verify the interpolation result
docker-build:
  script:
    - echo "IMAGE=$IMAGE"
    - test -n "$IMAGE"

create-release:
  stage: release
  image: registry.gitlab.com/gitlab-org/cli:latest
  script: echo "Creating release $CI_COMMIT_TAG"
  rules:
    - if: $CI_COMMIT_TAG =~ /^\d+\.\d+\.\d+$/
  release:
    tag_name: $CI_COMMIT_TAG
    description: "Release $CI_COMMIT_TAG of components in $CI_PROJECT_PATH"
EOF
git add -A && git commit -m "feat: python-test and docker-build components" && git push -u origin main
glab ci status --wait
(success) • 01m 12s   main
┌ lint ── ✓ ruff
├ test ── ✓ pytest: [3.13]
└ build ─ ✓ docker-build

docker-build Jobs are defined by the component; the main file only overrides script (deep merge of hashes, whole replacement of arrays — the merge rules from lesson 2). create-release rule only matches pure semantic-version tags.

3. Mark as a Catalog project and publish 1.0.0
glab api graphql -f query="mutation { catalogResourcesCreate(input: {projectPath: \"$COMP_PROJECT\"}) { errors } }"
git tag -a 1.0.0 -m "python-test, docker-build 1.0.0" && git push origin 1.0.0
glab ci status -b 1.0.0 --wait
glab release list
{"data":{"catalogResourcesCreate":{"errors":[]}}}
(success) • 01m 20s   1.0.0
Showing 1 release on mygroup-lab/platform/ci-components
NAME    TAG     CREATED
1.0.0   1.0.0   about 1 minute ago

GraphQL change catalogResourcesCreate Marked in the API reference as Experiment; the official way is the UI: Settings → General → Visibility, project features, permissions → turn on “CI/CD Catalog project” (requires Owner). Afterwards, in Search or go to → Explore → CI/CD Catalog you can see the project (private projects are visible only to members).

4. Replace python-lint / unit-test from lesson 2 in myapp (branch feat/use-components)
cd ~/gitlablab/myapp && git switch -c feat/use-components
python3 - <<'EOF'
import re, pathlib
p = pathlib.Path(".gitlab-ci.yml"); s = p.read_text()
inc = '''include:
  - component: $CI_SERVER_FQDN/mygroup-lab/platform/ci-components/python-test@1.0.0
    inputs:
      python_versions: ["3.12", "3.13"]
      coverage_min: 70

'''
s = inc + s
# Delete the python-lint and unit-test jobs written in lesson 2 (up to the next top-level key)
for job in ("python-lint", "unit-test"):
    s = re.sub(r'(?ms)^%s:\n.*?(?=^\S)' % re.escape(job), '', s)
s = s.replace("needs: [python-lint]", "needs: [ruff]").replace("needs: [unit-test]", "needs: [pytest]")
p.write_text(s)
EOF
glab ci lint && git commit -am "ci: use python-test component 1.0.0" && git push -u origin HEAD
glab mr create -t "ci: use python-test component" -d "Changelog: changed" -y
glab ci status --wait
✓ CI/CD YAML is valid!
(success) • 03m 01s   refs/merge-requests/3/head
┌ lint ── ✓ ruff  ✓ secret_detection
├ test ── ✓ pytest: [3.12]  ✓ pytest: [3.13]  ✓ integration-test
└ build ─ ✓ build-image

The job-name replacement in the script is written for the lesson 2 file; if your file differs, edit it by hand. Changelog: changed Writing it in the MR description is just a reminder; what actually feeds the changelog is the commit message trailer in it (Module 3). Merge the MR (Maintainer).

5. Publish 1.1.0 and try partial versions: in the component project, add python-test input pytest_args (default ""), then merge and tag 1.1.0; change the myapp reference to @1, and in the pipeline log using python-test@1.1.0 shows it resolved to the latest 1.x.
Verify In the myapp pipeline's pytest job log, look for using python-test@1.0.0 (from $[[ component.version ]]); on the Catalog page, you can see the input tables of both components.

Case 1: “YAML drift” across 40 microservices

Problem: each service copied a set of test and build YAML; after half a year there were 11 Python image versions and 3 coverage thresholds, and when the security team asked to uniformly add a signing step, 40 repositories had to be changed. Approach: The platform team publishes python-test / docker-build components; services switch to @1; component 1.4.0 adds a signing step, and all services get it automatically on their next pipeline run. Limitation:@1 means trusting every minor version from the component maintainer. Pair it with MR approvals, protected branches, and signed commits in the component project (official “component maintainer security practices”).

Case 2: ~latest introduces a breaking change

Problem: A team used @~latest to reference a third-party component; the author released 2.0.0, which removed an input, and on Monday morning all pipelines reported unknown input arguments. Approach: changed to @1, and use tools such as Renovate to open MRs that upgrade component versions. Lesson: official advice: pin third-party components to a commit SHA (best), or a full version, and audit the component source and the tokens it will touch.

Case 3: component job name collision

Problem: The consumer already has a job named pytest job; after adding the component, the two get merged, so the script comes from the main file and the matrix from the component, and only half the tests run. Approach: The component provides job_prefix an input for this (the official OpenTofu component already has job_name_prefix), or the consumer renames its own job.

Common errors and fixes

This GitLab CI configuration is invalid: Component 'gitlab.com/mygroup-lab/platform/ci-components/python-test@~latest' - content not found

Cause:~latest / partial versions only match versions published in the Catalog, and the project has not published any yet (or is not a Catalog project); it may also be a misspelled component name or path, or you lack the Reporter role on the private component project.

glab release list -R "$COMP_PROJECT"          # Are there any Releases with semantic versions?
glab api "projects/$(enc "$COMP_PROJECT")/repository/tree?path=templates" | jq -r '.[].name'

Fix: publish a version (official troubleshooting advice), or temporarily use a full version or SHA.

python-test: unknown input arguments: python_version

Cause: Passed a key that does not exist in component spec:inputs (it should be python_versions), or an input was removed when upgrading to a new major version. Fix: correct it against the input table in the component README or Catalog; pin the version to prevent unwanted upgrades.

`coverage_min` input: provided value is not a number

Cause:type: number 's input received a string (e.g., "high"). Similarly, a boolean input received yes, not in options list, not matching regex. Fix: pass values by type; in YAML, 70 is a number,"70" is a string.

Build component error: Spec must be a valid json schema (release job failed)

Cause: a component file has an empty spec:inputs:. Fix: when no inputs are needed, write only spec: and then add --- (official troubleshooting example).

The release job succeeded, but the project cannot be found in the Catalog

Checklist:① whether the “CI/CD Catalog project” toggle is turned on; ② whether the project has a description; ③ whether the tagged commit has a root-level README.md and at least one templates/ component; ④ whether the tag is a semantic version (1.0.0, not v1); ⑤ whether the Release is created by the release keyword in CI (Releases created via the Releases API are not published to the Catalog); ⑥ private projects are only visible to members.

jobs:pytest:rules:rule if invalid expression syntax

Cause: the input is interpolated into rules:if — it becomes an unquoted string, for example if: $CI_COMMIT_REF_NAME == main. Fix: write it as if: $CI_COMMIT_REF_NAME == "$[[ inputs.branch ]]"; when using a function, wrap the entire expression in single quotes as well.

Command-line tasks
1. Use one command to list the published versions of the component project and output only the tag names.
glab api "projects/$(printf %s "$COMP_PROJECT" | jq -sRr @uri)/releases" | jq -r '.[].tag_name'
2. Write, for the component project's own pipeline, an include snippet that tests docker-build the component's current commit.
include:
  - component: $CI_SERVER_FQDN/$CI_PROJECT_PATH/docker-build@$CI_COMMIT_SHA
    inputs:
      push: false
Scenario analysis
The security team requires that all services use reviewed component versions, but does not want 40 teams to upgrade manually for every patch. How would you design this?

Component project: protected main (push: No one, MR approval, signed commits), protected tags (only platform maintainers can publish versions), and the tag pipeline runs component self-tests before release. Consumers reference @1 (only receive 1.x patches and minor versions); major version upgrades go through bot MRs. Pin external third-party components to a commit SHA and review the diff in the upgrade MR. You can also enforce “a certain component must be used” with lesson 6's pipeline execution policies (Ultimate).

Verified instructional videos

▶
Talk: Efficient DevSecOps workflows with reusable CI/CD components — GitLab Unfiltered
English · speech referenced in the official component docs: designing and reusing components
▶
NEW GitLab CI CD components explained — Christian Lempa
English · hands-on demo of components, inputs, and the Catalog (recorded earlier; version rules follow this lesson)

Official docs

Video storyboard script (about 60 seconds)

This courseware cannot directly generate video or MP3; the storyboard and narration below can be handed to a video tool.

Shot 1 · 0–15s
Visual: the same YAML across 40 repositories gradually changes color (drift), merging into one “component” block with an interface plug.
Narration: copy-pasted pipelines drift; a component packages the interface, implementation, and version together.
Shot 2 · 15–40s
Visual: inputs in the include line fly one by one into the spec table; green checkmarks and red crosses appear in turn (unknown key, type error).
Narration: inputs are validated when the pipeline is created. A misspelled name or wrong type means the pipeline never starts.
Shot 3 · 40–60s
Visual: tag 1.0.0 → release job → Catalog card; the consumer's @1 pointer slides to 1.1.0.
Narration: push a semantic-version tag, and the release keyword publishes it to the Catalog; consumers write @1 to automatically get the latest 1.x version.
or score ≥ 70% in the quiz

Module 2 · Parent-child pipelines and multi-project pipelines

06:00 – 13:00 · One trigger job creates another pipeline; strategy determines whether downstream results can “flow back”
7 minFreestrategy: mirror (18.2+) · depend no longer recommended★★★★★
Learning goals
  • Distinguish parent-child pipelines (same project, same ref, same SHA) from multi-project pipelines (another project, default branch or a specified branch), and know how each affects ref status and the pipeline list.
  • Write trigger:include include (local / project / component / artifact, up to 3 files),trigger:project + branch,trigger:inputs,trigger:forward.
  • Accurately predict trigger job and upstream pipeline status when not writing strategy,strategy: depend,strategy: mirror is used, including manual jobs,allow_failure, and edge cases such as a downstream that cannot be created.
  • Use dynamic child pipelines to generate jobs for “changed services,” and know the nesting depth, pipeline-tier scale limits, and permission restrictions.
Prerequisites: Module 1 (components), lesson 2's rules / needs / artifacts. Importance:★★★★★

What: two kinds of downstream pipelines

parent-child pipelinemulti-project pipeline
Syntaxtrigger: include: …trigger: project: mygroup-lab/platform/deploy-config (can add branch)
Run inthe same project, same ref, same commit SHAdownstream project; by default, the default branch of the downstream project; branch can specify a branch or tag
$CI_PIPELINE_SOURCEparent_pipelinepipeline
Pipeline listdoes not appear in the project's pipeline list; only visible in the parent pipeline's detailsappears in the downstream project's pipeline list
Effect on ref statusOnly when strategy is set does it affect that ref's statusaffects the downstream project's ref status; if strategy is not set, it does not affect the upstream ref
interruptible Auto-cancelwhen a new pipeline on the same ref starts, it is canceled along with the parent pipelineis not canceled by new upstream pipelines (it can be canceled when the downstream project has its own new pipeline)
Nestingup to two levels child pipelines (parent → child → grandchild)are independent of each other, with no nesting limit
Permissionssame as the parent pipelineTriggering the upstream pipeline user must have permission to run pipelines in the downstream project; when targeting a protected branch, they also need merge or push permission on that branch.

By default, one pipeline level can have up to 1,000 downstream pipelines (adjustable on self-managed). A trigger job does not use a runner; it can only use a limited set of keywords: allow_failure,extends,needs (cannot needs:project),parallel,rules,stage,trigger,variables,when (on_success / on_failure / always / manual),resource_group,environment.

How: strategy determines how status propagates (core of this module)

CaseNo strategystrategy: depend (official: not recommended)strategy: mirror (18.2+, recommended)
When the trigger job endsDownstream is created successfully→ passedwaits for downstream to finishwaits for downstream to finish
When later stages startImmediately (in parallel)After downstream succeedsAfter downstream succeeds
A downstream job failstrigger remains passed; upstream may be all greenfailedfailed
A failed downstream job with allow_failure: truepassedshows success (downstream is treated as successful)same as downstream status
Downstream has a blocking manual job waitingpassedshows running (waits indefinitely)same as downstream (waiting for manual action)
downstream has an optional manual jobdoes not affect downstream status or the trigger job (per the docs)
downstream cannot be created at all (permissions, configuration error, rules that leave downstream empty)trigger job failed (regardless of strategy)
the parent pipeline is automatically canceled when the child pipeline fails——Both parent and child configure workflow:auto_cancel:on_job_failure: all and the trigger uses mirror only then will
Why does this lesson still cover depend? Many existing pipelines, blog posts, and this lesson's task list still use strategy: depend. The official trigger:strategy reference now states: depend 's trigger job status “is not always consistent with downstream” (manual waiting shows running, allow_failure failures show success); it is recommended to switch to mirror. New pipelines should use mirror; for older pipelines, just know the differences between depend — just know these two differences. GitLab 19.5 supports both.

How variables and inputs are passed to downstream

  • Top-level variables and the trigger job's own variables defaults are passed down as trigger variables (trigger:forward:yaml_variables: true).
  • Pipeline variables (entered manually when running, from scheduled jobs,needs job dotenv variables) by default are not passed; you need to trigger:forward:pipeline_variables: true; forwarded variables are not automatically forwarded to grandchild pipelines.
  • Runner config.toml environment variables and predefined “job-only” variables are not available in trigger jobs.
  • Available since 17.11: trigger:include:inputs (child) and trigger:inputs (multi-project) to the downstream configuration's spec:inputs values — safer than variables, because they have types and validation.
  • In child pipelines, $CI_PIPELINE_SOURCE is always parent_pipeline: to make child jobs run only when the parent pipeline is an MR pipeline, use if: $CI_MERGE_REQUEST_ID (the parent pipeline's CI_MERGE_REQUEST_* will be passed to the child pipeline).

When: when to split

  • Parent-child: multi-component monorepos trigger by directory; turn a group of jobs into a single status; run generated configuration (dynamic child pipelines); put each IaC environment in its own child pipeline (Module 7's trigger_in_child_pipeline).
  • Multi-project: after the application repo finishes building, notify the deployment repo or end-to-end test repo; handoffs between projects owned by different teams.
  • Don't split: when there are only a few jobs and you just want it to look tidy, use needs and stages are enough; downstream pipelines add troubleshooting and permission complexity.

Comparison with similar technologies

GitLabGitHub ActionsAzure PipelinesJenkins
Trigger another pipelinetrigger:include / trigger:projectReusable workflows uses: / workflow_dispatch + APITemplates / resources.pipelines triggerbuild job: 'x', wait: true
waits and inherits statusstrategy: mirrorreusable workflows are naturally synchronouspipeline resource triggers are asynchronouswait: true, propagate: true
Common misconceptions① “A green trigger job means downstream succeeded” — not true; without strategy it only means “downstream was created successfully.” ② “The child pipeline runs on another commit” — no, same SHA and same ref. ③ “A child pipeline can use $CI_PIPELINE_SOURCE == "merge_request_event"” — it is always parent_pipeline. ④ “A dynamic child pipeline's YAML can use variables in include paths” — no; the docs explicitly do not support this. ⑤ “With a CI_JOB_TOKEN allowlist, you can trigger downstream” —trigger:project no — what matters is the trigger user's permission in the downstream project; the allowlist affects needs:project pulling artifacts (Premium) and similar uses.

Pipeline topology in this lesson

mygroup-lab/myapp (parent pipeline · main · SHA 8f3c2a1b) ruff · pytest build-image trigger: include:ci/e2e.yml · mirror trigger: include:artifact (dynamic) trigger: project:platform/deploy-config · mirror release-notes (later stage) child pipeline e2esame project · same ref · same SHASOURCE = parent_pipelinejobs: api-e2e, ui-e2enot shown in pipeline list Dynamic child pipelinegenerate-config job→ generated.yml (artifact)one job per changed serviceinclude in YAML cannot use variables multi-project: deploy-configSOURCE = pipeline · default branch maininputs: environment · variable: IMAGE_TAGappears in deploy-config's pipeline listtriggering user needs run permission in downstream
Figure 2-1: One parent pipeline triggers a static child, a dynamic child, and a multi-project downstream simultaneously

Status propagation of strategy

No strategypassed as soon as created depend / mirrorwait for downstream and write back status Downstream pipelinerunning → failed / success Status write-back upstream trigger job → upstream pipeline mirror: exactly matches downstreamdepend: manual wait → runningdepend: allow_failure failure → successnone: no write-back (dashed line does not exist)
Figure 2-2: Downstream status is written back to the trigger job only when strategy is configured

Core animation: status propagation from parent → child / multi-project pipeline

First choose strategy, then choose a scenario, then click “Auto play” or “Next.” The three columns are the parent pipeline (myapp), the child pipeline (ci/e2e.yml), and the multi-project downstream (deploy-config). The table below shows the trigger job and parent pipeline status in real time; the log shows what GitLab does at each step.

strategy:
Scenario:
Parent pipeline · myapp
Child pipeline · ci/e2e.yml
Multi-project · deploy-config
Select a strategy and a scenario.
$ # GitLab event log

Keywords and commands at a glance

SyntaxPurposeNotes
trigger: include: ci/e2e.ymlStatic child pipelinecombine up to 3 configuration files
trigger: include: [{artifact: generated.yml, job: generate-config}]Dynamic child pipelinepath resolved by GitLab (on Linux, use /); include in the generated YAML cannot use variables
trigger: include: [{component: …@1.0.0, inputs: {…}}]Use a component as the child pipeline configurationaccess rules same as include:component
trigger: project: path + branch: branch nameMulti-project pipelineproject / branch supports variable expansion (excluding job-only variables)
trigger: strategy: mirrorwaits for and mirrors downstream status18.2+; depend still available but not recommended
trigger: forward: {yaml_variables, pipeline_variables}control which variables are forwardeddefault true / false
glab ci view / glab ci get -b mainView pipeline (including downstream bridge jobs)glab ci get output JSON
glab api projects/:id/pipelines/:pid/bridgeslist trigger (bridge) jobs and their downstream pipelinesField downstream_pipeline

Three trigger jobs added to the parent pipeline (myapp's .gitlab-ci.yml snippet)

stages: [lint, test, build, verify, downstream, release]

e2e:
  stage: verify
  needs: [build-image]
  trigger:
    include: ci/e2e.yml
    strategy: mirror            # for the differences from the old strategy: depend syntax, see “Concepts”
  variables:
    IMAGE: $CI_REGISTRY_IMAGE:$CI_COMMIT_SHORT_SHA   # YAML variables are forwarded to child pipelines by default
  rules:
    - if: $CI_COMMIT_BRANCH == $CI_DEFAULT_BRANCH
    - if: $CI_PIPELINE_SOURCE == "merge_request_event"

generate-config:
  stage: verify
  image: python:3.13-slim
  script:
    - python3 ci/gen_child.py > generated.yml
    - cat generated.yml
  artifacts:
    paths: [generated.yml]
    expire_in: 1 day

per-service:
  stage: verify
  needs: [generate-config]
  trigger:
    include:
      - artifact: generated.yml
        job: generate-config
    strategy: mirror

deploy-config:
  stage: downstream
  trigger:
    project: mygroup-lab/platform/deploy-config
    branch: main
    strategy: mirror
    inputs:
      environment: dev            # static value: use inputs, validated against options
  variables:
    IMAGE_TAG: $CI_COMMIT_SHORT_SHA   # runtime value: use a variable (trigger variables are forwarded by default and expanded downstream)
  rules:
    - if: $CI_COMMIT_BRANCH == $CI_DEFAULT_BRANCH

child pipeline ci/e2e.yml

workflow:
  rules:
    - if: $CI_PIPELINE_SOURCE == "parent_pipeline"

api-e2e:
  image: $IMAGE                       # from the trigger job variable in the parent pipeline
  script:
    - cd /app && gunicorn -b 127.0.0.1:5000 app:app --daemon && sleep 3
    - python -c "import urllib.request as u; assert u.urlopen('http://127.0.0.1:5000/healthz').read()==b'ok'"

ui-e2e:
  image: python:3.13-slim
  script: echo "UI smoke test (placeholder)"
  rules:
    - if: $CI_MERGE_REQUEST_ID          # only run when the parent pipeline is an MR pipeline
      allow_failure: true

generator ci/gen_child.py (generates jobs only for changed directories)

import os, subprocess, sys

base = os.environ.get("CI_MERGE_REQUEST_DIFF_BASE_SHA") or os.environ.get("CI_COMMIT_BEFORE_SHA", "")
if not base or set(base) == {"0"}:          # first push of a new branch: before SHA is all zeros
    base = "HEAD~1"
changed = subprocess.run(["git", "diff", "--name-only", base, "HEAD"],
                         capture_output=True, text=True).stdout.split()
services = sorted({p.split("/")[0] for p in changed if p.split("/")[0] in ("app.py", "tests", "docs")})
print("stages: [check]")
if not services:                            # a child pipeline cannot be empty, otherwise the trigger job fails
    print("noop:\n  stage: check\n  script: echo nothing changed")
for s in services:
    name = s.replace(".", "-")
    print(f"check-{name}:\n  stage: check\n  image: python:3.13-slim\n  script: echo checking {s}")

Shallow clone (default GIT_DEPTH 20), the older base commit may not exist; you can set generate-config in GIT_DEPTH: 0. The generator must output at least one job, otherwise it reports “downstream pipeline can not be created, the resulting pipeline would have been empty.”

Downstream deploy-config's .gitlab-ci.yml (receives parameters via spec:inputs)

spec:
  inputs:
    environment:
      default: dev
      options: [dev, prod]
---
render:
  image: alpine:3.22
  rules:
    - if: $CI_PIPELINE_SOURCE == "pipeline"
  script:
    - echo "deploy myapp:${IMAGE_TAG} to $[[ inputs.environment ]] (upstream $CI_PIPELINE_SOURCE)"
    - echo "$IMAGE_TAG" | grep -Eq '^([0-9a-f]{8}|[0-9]+\.[0-9]+(\.[0-9]+)?)$'   # only accept a short SHA or a version number

Official advice: when using inputs to configure a “new pipeline,” always provide default values; otherwise this project's own branch or MR pipelines may fail to start because required inputs are missing. Division of labor: static, enumerable parameters (environment names) use trigger:inputs, enjoying options validation; values known only at runtime (the short SHA) are passed via trigger variables; the downstream checks the format itself. alpine:3.22 Example tags only.

View bridge jobs and downstream pipelines

PID=$(glab ci get -b main -F json | jq -r .id)
glab api "projects/$(enc "$GL_PROJECT")/pipelines/$PID/bridges" \
  | jq -r '.[] | [.name, .status, (.downstream_pipeline.project_id|tostring), .downstream_pipeline.status] | @tsv'
e2e             success  12345678  success
per-service     success  12345678  success
deploy-config   success  71000002  success

Lab 2: parent-child + dynamic child + multi-project (about 15 min)

1. Prepare the downstream project deploy-config
cd ~/gitlablab/deploy-config
# Save the deploy-config .gitlab-ci.yml from the “Commands” tab
git add -A && git commit -m "ci: accept image_tag/environment inputs" && git push -u origin main
glab ci status --wait     # the project's own main pipeline: if render does not meet rules, the pipeline is not created or is empty; this is normal
2. In myapp, add three trigger jobs (branch feat/downstream): add ci/e2e.yml,ci/gen_child.py, and merge the snippet from the “Commands” tab into .gitlab-ci.yml (stages: add downstream,release).
cd ~/gitlablab/myapp && git switch main && git pull && git switch -c feat/downstream
mkdir -p ci   # write ci/e2e.yml and ci/gen_child.py
glab ci lint
git add -A && git commit -m "ci: child, dynamic child and multi-project pipelines

Changelog: added" && git push -u origin HEAD
glab mr create -t "ci: downstream pipelines" -d "e2e child + dynamic child" -y
glab ci status --wait
(success) • 04m 10s   refs/merge-requests/4/head
├ verify ── ✓ smoke  ✓ e2e (child: api-e2e, ui-e2e)  ✓ generate-config  ✓ per-service (child: check-app-py)

In MR pipelines, the deploy-config job's rules are not satisfied (it only runs on main), so it does not appear. The Changelog: added will be picked up by the Module 3 changelog.

3. Cause a failure and observe mirror: in ci/e2e.yml the api-e2e file, add - exit 1 and push. In the parent pipeline, e2e turns red and later stages stop running; after reverting, try again with strategy removed: e2e turns green while the child pipeline is red. This is the risk of not writing strategy.
4. Merge into main and verify the multi-project pipeline
glab mr merge --yes                 # run by a Maintainer
git switch main && git pull && glab ci status --wait
glab ci list -R "$DEPLOY_PROJECT" | head -3
glab ci trace render -R "$DEPLOY_PROJECT" | grep deploy
State     IID   Ref    Created
(success) #3    main   (about 1 minute ago)
deploy myapp:8f3c2a1b to dev (upstream pipeline)
5. Negative permission test (optional): have a colleague who is only a Developer on myapp and has no role on deploy-config push to an MR and then merge (or observe the main pipeline it triggers): deploy-config The job fails, with a message that it lacks permission to create the downstream pipeline.
Verify On the right side of the parent pipeline details page, three downstream cards appear; deploy-config 's pipeline list has pipelines whose source is “pipeline”; child pipelines do not appear in myapp's pipeline list.

Case 1: the “full pipeline” of a monorepo

Problem: One repo with 25 services; every commit runs 300 jobs. Approach: Dynamic child pipelines: generate-config based on git diff , generate jobs only for changed services; trigger uses mirror; or one static child pipeline per service + rules:changes. Limits: child pipelines nest at most two levels; include in generated configuration cannot use variables; the generator must handle the “no changes” case.

Case 2: green parent pipeline, red deployment

Problem: The application repo triggers the deployment repo with a multi-project pipeline, without strategy. The deployment failed, but after the MR was merged, the application repo's main stayed green, and production was only found to be out of date several days later. Approach: Add strategy: mirror, and in the deployment repo's jobs, clearly specify the environment and resource_group. Lesson: For any step that “hands off to another project,” decide whether the status needs to flow back.

Case 3: depend downstream pipeline “stays running forever”

Problem: The child pipeline has a when: manual and allow_failure: false (blocking-type) approval job; the parent's trigger job kept showing running, and the on-call colleague thought the runner was stuck. Approach: switch to mirror (shows as waiting for manual action, consistent with downstream), or move the approval to the parent pipeline; understand that with a blocking manual job, the trigger does not finish until that job runs.

Common errors and fixes

downstream pipeline can not be created, the resulting pipeline would have been empty. Review the rules configuration.

Cause: all jobs in the child / downstream configuration rules do not satisfy $CI_PIPELINE_SOURCE == "merge_request_event" (common cause: a child job wrote ). Fix: parent_pipeline for the child pipeline, use $CI_MERGE_REQUEST_ID or

; the dynamic generator must ensure at least one job.

trigger job fails: No permissions to trigger downstream pipeline / downstream project not found Cause:

glab api "projects/$(enc "$DEPLOY_PROJECT")/members/all/$(glab api user | jq .id)" | jq '{username, access_level}'
glab api "projects/$(enc "$DEPLOY_PROJECT")/protected_branches/main" | jq '.merge_access_levels'
downstream pipeline can not be created, Ref is ambiguous

The user who triggers the upstream pipeline has no permission to run pipelines in the downstream project; the downstream target is a protected branch and the user cannot merge or push; or the project path is wrong (private projects appear as “not found” to users without permission). Cause: main The downstream project has a branch and a tag with the same name (for example, both called 1.0 or ). Fix: branch: delete or rename one of them;

when only the name is given, GitLab cannot tell which one is meant.

Variables are empty in the child pipeline / variables in the trigger:include path are not expanded Cause: forward:pipeline_variables: true pipeline variables are not forwarded by default (need trigger:include ); only configuration-level variables can be used in the path; predefined variables take the child pipeline's values, and environment-scoped variables take unscoped values. Fix: trigger:include:inputs use

to pass parameters.

jobs:per-service config contains unknown keys: script (or image) Cause: script trigger jobs can only use a limited set of keywords and cannot have image,artifacts,needs:project,Fix: move the script into a preceding job.

Parent pipeline status inconsistent with child pipeline (depend)

Cause:depend 's known behavior: downstream shows running while waiting for a manual job; a failed downstream job allow_failure: true shows success. Fix: change to strategy: mirror (18.2+).

Command-line tasks
1. List the names, statuses, and downstream pipeline statuses of all bridge jobs in the latest pipeline on main.
PID=$(glab ci get -b main -F json | jq -r .id)
glab api "projects/:id/pipelines/$PID/bridges" | jq -r '.[] | "\(.name)\t\(.status)\t\(.downstream_pipeline.status)"'
2. Write a trigger job that triggers deploy-config for v* tag branches, and also forwards the pipeline variables entered during manual runs.
deploy-prod:
  stage: downstream
  trigger:
    project: mygroup-lab/platform/deploy-config
    branch: main
    strategy: mirror
    forward:
      pipeline_variables: true
    inputs:
      environment: prod
  variables:
    IMAGE_TAG: $CI_COMMIT_SHORT_SHA
  rules:
    - if: $CI_COMMIT_TAG =~ /^v\d+\.\d+/

GitLab variable expansion does not support shell ${VAR#v} syntax; when you need to strip the v from the version number, compute it in a preceding job with shell, write it to dotenv, and then forward it together with forward:pipeline_variables: true (dotenv variables are pipeline variables).

Scenario analysis
A parent pipeline has trigger job A (no strategy) that triggers a child pipeline, and tests in the child pipeline fail. What is the parent pipeline's status? Can the MR be merged? How do you change it?

Trigger job A is passed as soon as the child pipeline is created successfully, so the parent pipeline may be overall success; the “pipeline must succeed” check looks at the parent pipeline, so the MR can be merged; the failing test is bypassed. Change it to strategy: mirror (or the old depend syntax); then A waits for the child pipeline and becomes failed, the parent pipeline fails, and the MR is blocked.

Verified instructional videos

▶
Parent-Child Pipelines feature demo — GitLab Unfiltered
English · parent-child pipeline feature demo
▶
Create child pipelines using dynamically generated configurations — GitLab Unfiltered
English · official docs reference: dynamic child pipelines
▶
Nested Dynamic Pipelines — GitLab Unfiltered
English · official docs reference: nested dynamic child pipelines

These videos were recorded before strategy: mirror was introduced, so the depend in the demos should be read according to this lesson's explanations.

Official docs

Video storyboard script (about 60 seconds)

This courseware cannot directly generate video/MP3; the storyboard and narration below can be handed to a video tool.

Shot 1 · 0–20s
Visual: in the parent pipeline, a diamond-shaped trigger job sends out two lines: one goes to a child pipeline in the same project (the same commit hash highlighted), and one goes to another project.
Narration: a trigger job does not need a runner; it lets GitLab create another pipeline. Same project: a child pipeline; cross-project: a multi-project pipeline.
Shot 2 · 20–45s
Visual: the child pipeline turns red; three parent pipelines with three strategies side by side: no strategy stays green, depend turns red, mirror turns red; then it shows that while a manual job waits, depend shows running and mirror shows waiting.
Narration: without strategy, downstream failures do not flow back; depend and mirror both wait, but only mirror exactly matches the downstream status.
Shot 3 · 45–60s
Visual: the generate-config job outputs a YAML, which becomes a child pipeline with only two jobs.
Narration: a dynamic child pipeline generates its configuration from a job, creating jobs only for the parts that changed.
or score ≥ 70% in the quiz

Module 3 · Releases, tags, and changelogs

13:00 – 21:00 · Tags belong to Git, Releases belong to GitLab: release notes, assets, milestones, and evidence are all attached to a Release
8 minFreerelease-cli deprecated → glab★★★★
Learning goals
  • Explain the relationship among Git tags, protected tags, Releases, milestones, and Release evidence; backfill a Release for the existing lesson 2 v1.0 tag.
  • You will create Releases in CI in two ways: release keyword (since GitLab 18.0 it is implemented by calling glab release create) and directly in a script with glab release create, and know the authentication method of each.
  • Use Changelog: Git trailers + the changelog API / glab changelog generate to auto-generate release notes, and understand its requirements for the tag format (vX.Y.Z).
  • Add asset links (images, packages) to a Release, and use permanent links /-/releases/permalink/latest, and use deployment freezes to prevent accidental releases.
Prerequisites: Lesson 1 protected tags, lesson 2 v1.0 tag pipeline. Importance:★★★★

What: tags and Releases

objectbelongs tocontentWho can create (set in this lesson)
Git tags (lightweight / annotated)Gitpoint to a commit; annotated tags also carry an author and a messageprotected tags *: Maintainer only
ReleaseGitLabname, release notes (Markdown), asset links, source archives, milestones, Release evidence, release dateDevelopers and above can create Releases; but to create a Release for a protected tag requires permission to create that tag
milestoneGitLaba set of issues / MRs; when linked, they are closed by default when a Release is created (glab --no-close-milestone can prevent this)Group milestones require Premium
Release evidenceGitLabJSON snapshot generated automatically at creation time (milestones, issues, etc.)automatic

How: two ways to create a Release in CI

release keywordin a script glab release create
imagejob $PATH must have glab: Docker executor uses registry.gitlab.com/gitlab-org/cli:latestsame as left
authenticationdefault CI_JOB_TOKEN; if the job defines GITLAB_TOKEN / GITLAB_ACCESS_TOKEN / OAUTH_TOKEN then those take precedenceset GLAB_ENABLE_CI_AUTOLOGIN: "true" use the job token; or GITLAB_TOKEN= with api scope access token. Do not set GITLAB_TOKEN to $CI_JOB_TOKEN (it is sent as a PRIVATE-TOKEN header and returns 404)
Execution timingscript After after_script before; created only if the script succeedsanywhere in the script
An existing Releaseis not updated; the job failsby default updates an existing Release (--no-update prevents this)
publish to the CI/CD Catalogmust use it (Module 1)Not possible (--publish-to-catalog is still an experimental feature and requires a feature flag)
Current status of release-cli (verified)release-cli Deprecated in GitLab 18.0, planned for removal in 20.0. release Since 18.0 the release keyword generates a glab release create script (feature flag ci_glab_for_release, GA in 18.4). If the Runner does not have glab at the required version (≥ 1.58.0), it falls back to release-cli and prints a warning; this fallback is also planned for removal in 20.0. Older images registry.gitlab.com/gitlab-org/release-cli:<version> Since v0.24.0, it bundles glab 1.58.0. For new jobs, always use the gitlab-org/cli image.

Changelog: commit trailer-driven

  • Only commits whose commit message contains a Changelog: <category> trailer go into the changelog; categories: added,fixed,changed,deprecated,removed,security,performance,other. With multiple commits in an MR, put the trailer in the first commit (only then does it survive a squash).
  • Two APIs: GET /projects/:id/repository/changelog (generation only; supported since 17.7 CI_JOB_TOKEN, supported since 19.1 .txt plain text) and POST …/changelog (generates and commits to CHANGELOG.md); CLI: glab changelog generate.
  • version Must be a semantic version (since 17.0 1.2.0 and v1.2.0 are equivalent). Without from , GitLab automatically finds the “previous stable version tag,” and only recognizes X.Y.Z / vX.Y.Z.
  • Configuration file .gitlab/changelog_config.yml: categories (title mapping),template,date_format,tag_regex (must produce major/minor/patch capture group, otherwise the tag is ignored),include_groups; parsing time limit 2 seconds.
Pitfalls when connecting to earlier lessons Tags in lessons 2 and 3 are two-part v1.0,v1.1,do not satisfy the default vX.Y.Z rule (missing a patch number), so the changelog API ignores them. Therefore: ① the first time this lesson generates the changelog for 1.2.0 the log, explicitly pass from (v1.1 or v1.0 's commit SHA); ② from this lesson on, use the three-part v1.2.0— the lesson 2 rule $CI_COMMIT_TAG =~ /^v\d+\.\d+/ still matches, and the image tag ${CI_COMMIT_TAG#v} becomes 1.2.0.

When: which releases should have a Release

  • versions visible externally (customers, other teams, component consumers).
  • versions that need to be audited for “what was released, which MRs were included, and where the artifacts are.”
  • Internal main deployments do not need a Release; that is a “deployment” (recorded on the environment page), not a “release.”

Comparison with similar technologies

GitLabGitHubAzure DevOps
Release objectRelease (tag-based) + evidence + milestonesRelease (tag-based) + auto-generated notesno object with the same name (Classic Release is a deployment pipeline)
creating in CIrelease release keyword / glab release creategh release createGitHub Release task or REST
changelogcommit trailer + APIauto notes based on PR labelsneeds a third party
Common misconceptions① “Pushing a tag creates a Release” — no; a Release must be created separately. ② “Deleting a Release deletes the tag” — no, the tag remains (conversely, deleting a tag removes the Release's anchor). ③ “Assets are uploaded into the Release” — the Release only stores links; files should go into the generic package registry or the container registry,glab release create --use-package-registry are automatically uploaded to the generic package registry. ④ “A release job can omit script” — it must have a script; you can use echo as a placeholder.

Data flow for a v1.2.0 release

Maintainergit tag -a v1.2.0Protected tag check Tag pipelineCI_COMMIT_TAG=v1.2.0build-image → :1.2.0 release-notes jobGET /repository/changelog.txt → release_notes.md release jobglab release createCI_JOB_TOKEN Release v1.2.0 (Deploy → Releases) Release notes: ### added (2 changes) · ### changed (1 change) Asset link: container image registry.gitlab.com/mygroup-lab/myapp:1.2.0 (image) myapp-src-1.2.0.tar.gz → generic package registry (package) · source archive (automatic) Milestone: v1.2 (closed after creation) · Release evidence JSON · permanent link /-/releases/permalink/latest Deployment freeze$CI_DEPLOY_FREEZE→ release job: when: never
Figure 3-1: the changelog is generated by the API from commit trailers; the release job writes it into the Release

How the changelog API determines the commit range

v1.0two-part → ignored v1.1two-part → ignored feat (Changelog: added) ci (Changelog: changed) docs (no trailer) HEAD → v1.2.0 First time: from = SHA of v1.1 (exclusive), to = HEAD (inclusive); thereafter: omit from, and it automatically finds v1.2.0
Figure 3-2: only commits with trailers enter the release notes; old two-part tags require an explicit from

Interactive: tag → Release pipeline, step-by-step replay

Pick a scenario and play it step by step to see what GitLab calls at each step (protected tag check, tag pipeline, changelog API, glab release, Release object). Failure scenarios stop where the real failure happens and show the original error.

Select a scenario to start.
$ # job log

Commands at a glance

CommandPurposeKey parameters
glab release create v1.0 -N "…"Create a Release for an existing tagIf the tag does not exist, need --ref; -F file read notes from a file
glab release create TAG -a '[{…}]'attach asset links (JSON)link_type: other / runbook / image / package
glab release create TAG ./dist/*.tar.gz --use-package-registryupload a file to the generic package registry and link it--package-name default release-assets
glab release list / view / download / deletemanage Releases-R specify project
glab changelog generate --version 1.2.0 --from SHApreview the changelog locallyglab ≥ 1.30; default trailer Changelog
GET /projects/:id/repository/changelog.txt?version=1.2.0generate plain-text log (19.1+)use in CI JOB-TOKEN header (17.7+)
POST /projects/:id/repository/changeloggenerate and commit to CHANGELOG.mdbranch,file,message
glab api projects/:id/freeze_periodsmanage deployment freezescron format freeze_start / freeze_end + time zone

1. Backfill a Release for lesson 2's v1.0

cd ~/gitlablab/myapp && git fetch --tags
glab release create v1.0 --name "myapp 1.0" \
  --notes "First version: Flask + Redis counter, image registry.gitlab.com/mygroup-lab/myapp:1.0" \
  --assets-links '[{"name":"container image 1.0","url":"https://gitlab.com/mygroup-lab/myapp/container_registry","link_type":"image"}]' \
  --milestone v1.0
glab release view v1.0
• Validating tag v1.0
• Creating or updating release for tag v1.0
✓ Release created: https://gitlab.com/mygroup-lab/myapp/-/releases/v1.0
✓ Closed milestone "v1.0"
myapp 1.0
…
ASSETS
container image 1.0   https://gitlab.com/mygroup-lab/myapp/container_registry

The tag already exists, so there is no need for --ref. --milestone v1.0 Link lesson 1's milestone and close it by default (to keep it open, add --no-close-milestone). v1.0 is a “past” version, so you can add --released-at "2026-11-10T12:00:00Z" to make it display as Historical release (dated example).

2. Write a commit with a trailer and preview the changelog locally

git log --format='%h %s%n%(trailers:key=Changelog,valueonly)' v1.1..HEAD 2>/dev/null || git log --format='%h %s%n%(trailers:key=Changelog,valueonly)' v1.0..HEAD
FROM=$(git rev-list -n1 v1.1 2>/dev/null || git rev-list -n1 v1.0)
glab changelog generate --version 1.2.0 --from "$FROM"
## 1.2.0 (2026-11-16)

### added (1 change)

- [ci: child, dynamic child and multi-project pipelines](mygroup-lab/myapp@4c1d9e2%E2%80%A6) ([merge request](mygroup-lab/myapp!4))

### changed (1 change)

- [ci: use python-test component 1.0.0](mygroup-lab/myapp@a7b3f10%E2%80%A6) ([merge request](mygroup-lab/myapp!3))

If the commits in modules 1 and 2 were squash-merged (lesson 1 set squash default_on), the trailer must appear in the squash commit message. Confirm this in the MR merge dialog, or keep only one commit with a trailer in the MR.

3. Two release jobs in the tag pipeline (snippet from myapp's .gitlab-ci.yml)

release-notes:
  stage: release
  image: alpine:3.22
  rules:
    - if: $CI_COMMIT_TAG =~ /^v\d+\.\d+\.\d+$/
  variables:
    GIT_DEPTH: 0
  script:
    - apk add --no-cache curl git >/dev/null
    - VERSION="${CI_COMMIT_TAG#v}"
    - PREV=$(git tag -l 'v*.*.*' --sort=-v:refname | grep -vx "$CI_COMMIT_TAG" | head -1)
    - FROM=${PREV:-$(git rev-list -n1 v1.1 2>/dev/null || git rev-list -n1 v1.0)}
    - |
      curl --fail-with-body -sS --header "JOB-TOKEN: $CI_JOB_TOKEN" \
        "$CI_API_V4_URL/projects/$CI_PROJECT_ID/repository/changelog.txt?version=$VERSION&from=$(git rev-list -n1 "$FROM")&to=$CI_COMMIT_SHA" \
        > release_notes.md
    - printf '\n\n**image**: `%s:%s`\n' "$CI_REGISTRY_IMAGE" "$VERSION" >> release_notes.md
    - cat release_notes.md
  artifacts:
    paths: [release_notes.md]

release:
  stage: release
  image: registry.gitlab.com/gitlab-org/cli:latest
  needs: [release-notes, build-image]
  rules:
    - if: $CI_COMMIT_TAG =~ /^v\d+\.\d+\.\d+$/ && $CI_DEPLOY_FREEZE == null
  script:
    - echo "Releasing $CI_COMMIT_TAG"
  release:
    tag_name: $CI_COMMIT_TAG
    name: "myapp ${CI_COMMIT_TAG}"
    description: ./release_notes.md
    milestones: ["v1.2"]
    assets:
      links:
        - name: "container image ${CI_COMMIT_TAG}"
          url: "https://gitlab.com/$CI_PROJECT_PATH/container_registry"
          link_type: image
        - name: "myapp-src-${CI_COMMIT_TAG}.tar.gz"
          url: "$CI_API_V4_URL/projects/$CI_PROJECT_ID/packages/generic/myapp/${CI_COMMIT_TAG}/myapp-src.tar.gz"
          link_type: package
  • Why release-notes computes from itself: old two-part tags are not automatically recognized by the API; after the new tag v1.2.0 is released, the next v1.3.0 will automatically start from it.
  • description: ./release_notes.md: paths are relative to $CI_PROJECT_DIR, file names must not contain spaces; the release job receives artifacts through needs .
  • Deployment freeze:$CI_DEPLOY_FREEZE only exists within the freeze window,== null so the release job does not appear during the freeze period.
  • Version prefix:release:name Variables in fields such as ${CI_COMMIT_TAG#v} are expanded by the shell where glab runs; it is safer to pre-compute them in the description file.

4. Set a deployment freeze from Friday night to Monday morning every week

glab api -X POST "projects/:id/freeze_periods" \
  -f freeze_start="0 18 * * 5" -f freeze_end="0 8 * * 1" -f cron_timezone="America/Toronto"
glab api "projects/:id/freeze_periods" | jq -c '.[] | {freeze_start, freeze_end, cron_timezone}'

Lab 3: backfill the v1.0 Release and publish v1.2.0 (about 15 min)

1. Backfill the v1.0 Release (Commands tab, part 1). In Deploy → Releases, you see v1.0 with the automatic “source code” asset and the image link.
2. Prepare milestone v1.2 and the generic package job
glab api -X POST "projects/:id/milestones" -f title=v1.2 | jq -r .web_url

The generic package in the asset links is uploaded by the package-src job from Module 4; if you do this module first, the link returns 404 for now, which does not prevent the Release from being created (the Release only stores links).

3. Add the release-notes / release jobs (branch feat/release, merged via MR). Add the trailer to the commit message:
git switch -c feat/release
# Edit .gitlab-ci.yml: release is already at the end of stages; paste part 3 of the Commands tab
glab ci lint
git commit -am "ci: automated releases with changelog

Changelog: added"
git push -u origin HEAD && glab mr create -t "ci: automated releases" -d "release keyword + changelog API" -y
4. Publish v1.2.0 (Maintainer, on main after merging)
git switch main && git pull
git tag -a v1.2.0 -m "myapp 1.2.0" && git push origin v1.2.0
glab ci status -b v1.2.0 --wait
glab release view v1.2.0 | head -20
(success) • 05m 02s   v1.2.0
├ build ── ✓ build-image
└ release ─ ✓ release-notes  ✓ release
myapp v1.2.0
## 1.2.0 (2026-11-16)
### added (2 changes)
- [ci: automated releases with changelog](%E2%80%A6) ([merge request](mygroup-lab/myapp!5))
- [ci: child, dynamic child and multi-project pipelines](%E2%80%A6) ([merge request](mygroup-lab/myapp!4))
### changed (1 change)
- [ci: use python-test component 1.0.0](%E2%80%A6) ([merge request](mygroup-lab/myapp!3))
**image**: `registry.gitlab.com/mygroup-lab/myapp:1.2.0`
5. Verify the permanent link and the release job log
curl -sI "https://gitlab.com/$GL_PROJECT/-/releases/permalink/latest" | grep -i '^location'   # private projects require login; open it in a browser
glab ci trace release | grep -E 'glab|release-cli|Release'
$ glab release create "v1.2.0" --name "myapp v1.2.0" --notes-file "./release_notes.md" …
✓ Release created: https://gitlab.com/mygroup-lab/myapp/-/releases/v1.2.0

The job log shows glab release create, indicating the Runner takes the new path from 18.0 onward (follow the actual log for the exact parameter form).

Verify The Releases page shows v1.0 and v1.2.0; milestone v1.2 is closed; docker pull registry.gitlab.com/mygroup-lab/myapp:1.2.0 succeeded.

Case 1: release notes written by hand always miss something

Problem: Before every release, the release manager goes through the MR list to write the notes and often misses fixes. Approach: Add a “Changelog trailer” reminder to the MR template; the squash commit message template includes Changelog: %{…}; the release job calls the changelog API. Another weekly job POST /repository/changelog commits the content to CHANGELOG.md. Limits: Commits without a trailer will not appear; check during review.

Case 2: migrating from release-cli

Problem: After upgrading to GitLab 18, the release job logs on self-managed runners show Warning: release-cli will not be supported after 20.0. Please use glab version >= 1.58.0.Approach: Change the job image from gitlab-org/release-cli to gitlab-org/cli; install glab on the host for the shell executor; jobs that call release-cli directly in scripts are rewritten to glab release create and set GLAB_ENABLE_CI_AUTOLOGIN.

Case 3: “automatic release” on Friday night

Problem: Someone tagged at 22:00 on Friday; the automatic release and deployment caused a production incident. Approach: deployment freeze window + release / deployment job rules $CI_DEPLOY_FREEZE == null; protected tags are restricted to the release owner.

Common errors and fixes

Error: glab command not found. Please install glab v1.58.0 or higher.

Cause:release the job's image has no glab, and there is no release-cli to fall back to. Fix:image: registry.gitlab.com/gitlab-org/cli:latest; install glab on the host for the shell executor.

404 Not Found (glab release create in CI)

Cause: You set GITLAB_TOKEN to $CI_JOB_TOKEN: glab sends it with a PRIVATE-TOKEN header, while the Releases API only accepts the job token in the JOB-TOKEN header. Fix: remove GITLAB_TOKEN, and set GLAB_ENABLE_CI_AUTOLOGIN: "true".

401 Unauthorized (release keyword)

Cause: the job defines GITLAB_TOKEN / GITLAB_ACCESS_TOKEN / OAUTH_TOKEN (possibly from a project or group variable); glab prefers it, but that token lacks api scope or has expired. Fix: unset that variable in the release job or replace it with a valid token.

Release already exists (release job failed)

Cause:release the release keyword does not update an existing Release, for example when the tag pipeline was rerun. Fix: this is expected behavior; to change the notes, use glab release create TAG -F notes.md (updates by default) or edit in the UI.

Changelog API returns 400: …unable to determine the previous version / needs from

Cause: no previous semantic-version tag was found (this lesson's v1.0/v1.1 is two-part). Fix: explicitly pass from=<SHA>; later use vX.Y.Z; or in .gitlab/changelog_config.yml write a custom tag_regex (must have major/minor/patch capture groups). (The exact error text depends on the actual response.)

Release notes are empty / only the title

Cause: none of the commits in the range has a Changelog: trailer; or the trailer was lost during squash merging. Diagnose:git log --format='%h %(trailers:key=Changelog)' FROM..HEAD.

Command-line tasks
1. Use the API to generate a plain-text changelog for 1.2.0, with the range from v1.1's commit to HEAD.
glab api "projects/:id/repository/changelog.txt?version=1.2.0&from=$(git rev-list -n1 v1.1)"
2. Replace the notes of the v1.2.0 Release with the contents of the local file notes.md.
glab release create v1.2.0 -F notes.md      # updates by default if it already exists (only --no-update prevents this)
Scenario analysis
The component project's version release used glab release create 1.1.0 (script approach); the Release page shows it, but 1.1.0 is not visible in the Catalog. Why? How do you fix it?

Catalog versions can only be created by the release keyword in a CI job; Releases created via the Releases API or glab scripts are not published to the Catalog. Fix: delete that Release (keep the tag), and in the tag pipeline use the release keyword in a job to re-create it (rerun the tag pipeline, or delete and re-push the tag).

Verified instructional videos

No verified video specifically covering GitLab Releases and the changelog API (with the new glab path) was found. The following general videos can serve as background:

▶
GitLab CI CD Tutorial for Beginners [Crash Course] — TechWorld with Nana
English · pipeline basics review (without Releases details)

Official docs

Video storyboard script (about 60 seconds)

This courseware cannot directly generate video/MP3; the storyboard and narration below can be handed to a video tool.

Shot 1 · 0–15s
Visual: a tag flag is planted on a commit; an empty Release card beside it gradually fills in: notes, assets, milestones.
Narration: a tag is only a pointer; the Release is the version people read: notes, artifact links, milestones, and evidence.
Shot 2 · 15–40s
Visual: lines marked Changelog in the commit list glow and get pulled into a Markdown document, grouped by added and changed.
Narration: write a Changelog colon line such as added in the commit message, and GitLab's changelog API files it under the matching category.
Shot 3 · 40–60s
Visual: the release-cli icon fades out and the glab icon takes over; the release job generates a Release card.
Narration: the release keyword now runs through glab, authenticated with the job token; release-cli is deprecated and will be removed in 20.0.
or score ≥ 70% in the quiz

Module 4 · Packages and the container registry

21:00 – 28:00 · Each project comes with a container registry and a package registry; without governance, they quietly consume the namespace's storage quota
7 minCleanup policies · protected container tags: FreeImmutable container tags: Ultimate★★★★
Learning goals
  • Use predefined variables CI_REGISTRY,CI_REGISTRY_IMAGE,CI_REGISTRY_USER,CI_REGISTRY_PASSWORD to push images, and use the job token to publish packages.
  • Walk through the cleanup policy in the official order: collect → exclude latest → name_regex → name_regex_keep → exclude those without a manifest → sort by creation time → keep keep_n → exclude those newer than older_than → exclude protected / immutable tags → delete.
  • Configure cleanup policies with the API (cadence,keep_n,older_than legal values), and use protected container tags to protect release versions.
  • Publish generic and PyPI packages, and configure package cleanup policies (duplicate asset retention count).
Prerequisites: Lesson 2 image tag scheme (short SHA / version number without v). Importance:★★★★

What: two registries

container registrypackage registry
Addressregistry.gitlab.com/mygroup-lab/myapp[/subpath]:tag ($CI_REGISTRY_IMAGE)$CI_API_V4_URL/projects/:id/packages/<format>/…
FormatOCI / Docker images (can also store OCI artifacts such as Helm OCI charts)generic, PyPI, npm, Maven, NuGet, Conan, Go proxy, Terraform modules, Helm, etc.
CI authenticationdocker login $CI_REGISTRY -u $CI_REGISTRY_USER -p $CI_REGISTRY_PASSWORD (job token)JOB-TOKEN: $CI_JOB_TOKEN header, or the format's own username gitlab-ci-token
Storage calculationlayers are deduplicated within the root namespace; only layers referenced by tagged image references are counted; untagged layers with no references within 24 hours are garbage-collected onlineEvery asset file counts; re-uploading the same name and version stacks assets
Automatic governancecleanup policies (by tag)cleanup policies (duplicate asset retention count; runs about every 12 hours)

How: the evaluation order of cleanup policies (official 10 steps)

  1. collect all tags in the repository;
  2. exclude latest (always kept);
  3. use name_regex (the ones to delete) to filter; non-matching ones are excluded;
  4. matching name_regex_keep (the ones to keep) exclusion;
  5. exclude tags with no manifest;
  6. sort by creation time;
  7. exclude the latest keep_n (per image name);
  8. exclude those newer than older_than ;
  9. exclude protected tags and immutable tags;
  10. delete the rest.

Mnemonic: keep rules take precedence: if any keep rule matches, the tag is kept; a delete rule must all be met to delete. Regexes are automatically anchored \A…\Z anchors and use RE2 syntax.

API parameters (container_expiration_policy_attributes)legal values
cadence1d,7d,14d,1month,3month
keep_n1,5,10,25,50,100
older_than1d,3d,7d,14d,30d,60d,90d,180d,365d,730d,1095d
name_regex / name_regex_keepRE2 regex; the delete regex cannot be empty (default .*)

Note: cleanup policies only delete tags, but underlying layers are handled by garbage collection (GitLab.com collects them online automatically; self-managed instances need an administrator to run GC). On GitLab.com each run has a limited time, so with many tags you may need several runs to finish deleting. For projects with no images at all, enabled policies are automatically disabled. Editing and saving a policy resets the run interval.

Protected and immutable container tags

Protected container tagsImmutable container tags
TierFree (17.11 GA)Ultimate (18.10 GA)
Purposerestrict who can push / delete matching tags (minimum role Maintainer / Owner / Administrator)matching tags after creation anyone cannot overwrite or delete
Quantityat most 5 rules per project, regex ≤ 100 charactersper official docs
andare both skipped by cleanup policies.

When: which registry to use

  • Runnable images and OCI artifacts → container registry.
  • Language-ecosystem libraries (installed by pip / npm) → the matching package registry.
  • Arbitrary binaries, source archives, Release assets → generic packages.
  • Temporary build outputs (only for later jobs) → CI artifacts (artifacts + expire_in), not the registry.

Comparison with similar technologies

GitLabGitHub Packages / GHCRAzure Artifacts / ACR
Automatic cleanupproject-level cleanup policies (UI / API)need an Action or API to delete versionsACR retention policies / tasks; artifact retention policies
Tag protectionprotected (Free) / immutable (Ultimate)no equivalent featureACR lock (write-enabled=false)
Common misconceptions① “keep_n: 10 means the repository has at most 10 tags”—it only exempts the latest 10 from the to-delete list; version tags matching keep regexes are counted separately. ② “A delete rule written as .* will delete latest” — latest is always kept. ③ “Storage drops immediately after deleting tags” — it has to wait for garbage collection and a usage refresh. ④ “Cleanup policies clean up packages” — no, packages have their own cleanup policies.

Tag lifecycle of myapp

main pipelinepush :8f3c2a1b (short SHA) v1.2.0 tag pipelinepush :1.2.0 MR pipelinebuild only, no push registry.gitlab.com/mygroup-lab/myapp 1.0 · 1.1 · 1.2.0 ← keep regex \d+\.\d+(\.\d+)? + protected tag rule 8f3c2a1b (2 days) ← newer than 14d: keep a7b3f10c … 1st–10th newest ← keep_n=10: keep 0d9e8c7b (45 days, 23rd newest) ← delete latest (if any) ← always kept Untagged layers: no reference for 24h → online GC Cleanup policy (daily) name_regex: .*name_regex_keep:(?:\d+\.\d+(?:\.\d+)?|main)keep_n: 10older_than: 14dcadence: 1dUsage quotas to view the effect
Figure 4-1 version-number tags are kept by both the regex and protection rules; short-SHA tags expire by “count + time”

Asset stacking in the package registry

generic package myapp / v1.2.0myapp-src.tar.gz (1st time)myapp-src.tar.gz (rerun, 2nd time)myapp-src.tar.gz (3rd time) Package cleanup policy“duplicate asset retention count” = 1runs about every 12 hours keeps only the latest 1 copysame package, same file name = duplicateor forbid duplicate uploads
Figure 4-2 repeatedly uploading the same name and version stacks assets; cleanup policies deduplicate by file name

Interactive: cleanup policy evaluator

On the left are a repository's tags (name and “created N days ago”); you can change the policy parameters above. Click “Evaluate step by step” to walk through the official 10 steps; at each step, excluded (kept) tags turn green, and the ones left at the end turn red (to be deleted). The default data comes from the examples in the official docs.

Click “Evaluate step by step.”
# evaluation log

Commands at a glance

CommandPurposeNotes
glab api -X PUT projects/:id --input policy.jsonSet cleanup policyin the JSON container_expiration_policy_attributes
glab api projects/:id | jq .container_expiration_policyView policy and next_run_at
glab api "projects/:id/registry/repositories?tags=true&tags_count=true"List container repositories and tagsread-only
glab api -X DELETE "projects/:id/registry/repositories/:rid/tags/:tag"Delete a single tagprotected tags require the matching role
glab api -X DELETE "projects/:id/registry/repositories/:rid/tags" -f name_regex_delete=… -f keep_n=…Bulk delete (one-time)parameter semantics same as cleanup policy
curl --header "JOB-TOKEN: $CI_JOB_TOKEN" --upload-file f "$CI_API_V4_URL/projects/$CI_PROJECT_ID/packages/generic/name/version/file"upload generic packageversion and file name have character restrictions
TWINE_USERNAME=gitlab-ci-token TWINE_PASSWORD=$CI_JOB_TOKEN twine upload --repository-url $CI_API_V4_URL/projects/$CI_PROJECT_ID/packages/pypi dist/*publish PyPI packagethe same name and version can be re-uploaded by default (can be forbidden in settings)
glab api "projects/:id/packages" | jq …list packages

1. Set a cleanup policy for myapp

cat > policy.json <<'EOF'
{ "container_expiration_policy_attributes": {
    "enabled": true,
    "cadence": "1d",
    "keep_n": 10,
    "older_than": "14d",
    "name_regex": ".*",
    "name_regex_keep": "(?:\\d+\\.\\d+(?:\\.\\d+)?|main)"
} }
EOF
glab api -X PUT "projects/$(enc "$GL_PROJECT")" --input policy.json -H "Content-Type: application/json" \
  | jq '.container_expiration_policy | {enabled, cadence, keep_n, older_than, name_regex_keep, next_run_at}'
{
  "enabled": true,
  "cadence": "1d",
  "keep_n": 10,
  "older_than": "14d",
  "name_regex_keep": "(?:\\d+\\.\\d+(?:\\.\\d+)?|main)",
  "next_run_at": "2026-11-17T09:41:00.000Z"
}

How to verify: UI: Settings → Packages and registries → Container registry → Cleanup policies shows the same rules. Common errors:keep_n: 3 values not in this list are rejected; in JSON, backslashes in regexes must be doubled. Production use: first use a larger older_than (such as 90d) and more specific delete regexes to observe several rounds, then tighten gradually (official advice).

2. Protect release version tags

Settings → Packages and registries → Container registry → Protected container tags → add a rule: matching \d+\.\d+(\.\d+)?, push minimum role Maintainer, delete minimum role Maintainer. After that, even if a Developer's MR or branch pipeline writes a bad script, it cannot overwrite 1.2.0; cleanup policies also skip it.

Relationship with the CI job token in CI docker push uses the identity of the user who triggered the pipeline. Protected v* Git tags can only be created by Maintainers, so when the tag pipeline pushes :1.2.0 , the user is a Maintainer anyway; the two layers of protection are consistent.

3. Publish a generic package in the tag pipeline (Release asset)

package-src:
  stage: release
  image: alpine:3.22
  rules:
    - if: $CI_COMMIT_TAG =~ /^v\d+\.\d+\.\d+$/
  script:
    - apk add --no-cache curl git >/dev/null
    - git archive --format=tar.gz -o myapp-src.tar.gz HEAD
    - |
      curl --fail-with-body -sS --header "JOB-TOKEN: $CI_JOB_TOKEN" --upload-file myapp-src.tar.gz \
        "$CI_API_V4_URL/projects/$CI_PROJECT_ID/packages/generic/myapp/${CI_COMMIT_TAG}/myapp-src.tar.gz"

The URL matches the asset link of the Release in Module 3, so the link on the Release page can be downloaded directly (private projects require login).

4. (Optional) Package myapp as a wheel and publish it to the PyPI registry

publish-pypi:
  stage: release
  image: python:3.13-slim
  rules:
    - if: $CI_COMMIT_TAG =~ /^v\d+\.\d+\.\d+$/
  script:
    - pip install -q build twine
    - python -m build
    - TWINE_USERNAME=gitlab-ci-token TWINE_PASSWORD=$CI_JOB_TOKEN python -m twine upload --repository-url "$CI_API_V4_URL/projects/$CI_PROJECT_ID/packages/pypi" dist/*

You need to pyproject.toml in [project] the name and version (can be generated from the tag). Install: pip install myapp --index-url https://__token__:<token>@gitlab.com/api/v4/projects/<project ID>/packages/pypi/simple.

Lab 4: cleanup policy + protected tags + generic package (about 12 min)

1. Observe the current repository
glab api "projects/$(enc "$GL_PROJECT")/registry/repositories?tags=true&tags_count=true" \
  | jq -r '.[] | "\(.location)  tags=\(.tags_count)  \([.tags[].name] | join(","))"'
registry.gitlab.com/mygroup-lab/myapp  tags=9  1.0,1.1,1.2.0,0d9e8c7b,4c1d9e2a,8f3c2a1b,a7b3f10c,c2d4e6f8,e1f2a3b4
2. First “rehearse”: use the evaluator to see which tags would be deleted. On the “Animation” tab, choose “myapp data,” set keep_n=1 and older_than=7d, and confirm that all version-number tags are green (kept).
3. Apply the cleanup policy (Commands tab, part 1) and protected tag rule (part 2, UI).
4. Add the package-src job and verify: after merging, on an already published v1.2.0 rerun the package-src job (or it runs automatically with the next version):
glab api "projects/$(enc "$GL_PROJECT")/packages?package_type=generic" | jq -r '.[] | "\(.name) \(.version) \(.status)"'
myapp v1.2.0 default
5. Package cleanup policy: Settings → Packages and registries → Package registry → “Manage storage used by package assets” → set duplicate asset retention count to 1. Rerun package-src once more; about 12 hours later only the latest asset remains.
6. View usage: Settings → Usage quotas → Storage, confirm the usage of Container Registry and Packages; Deploy → Container Registry shows the size of each repository (GitLab.com has the metadata database enabled).
Verifyglab api "projects/$(enc "$GL_PROJECT")" | jq .container_expiration_policy.enabled Return to true; a Developer trying to docker push …:1.2.0 is rejected.

Case 1: free namespace storage alerts

Problem: Every commit pushes a short-SHA image (about 150 MB, about 20 MB incremental after deduplication); after a year, the container registry takes tens of GB and the namespace approaches its quota. Approach: cleanup policy “keep version numbers + the latest 10 + 14 days”; MR pipelines only build without pushing (done in lesson 2); push debugging images to a prefixed subpath (such as $CI_REGISTRY_IMAGE/dev) and set a more aggressive delete regex.

Case 2: a cleanup policy deleted an image production was using

Problem: Production deployed by short-SHA tags (no version-number tags); after 30 days without a release, the cleanup policy deleted the tag of the running image; pulls failed when nodes were rebuilt. Approach: production deploys only version-number tags or digests; protected container tags protect \d+\.\d+(\.\d+)?; Ultimate can use immutable tags. Lesson: cleanup policies look at “tag name and age” and do not know which image is running.

Case 3: re-uploading the same version

Problem: The release job was rerun, and the same-version wheel of the PyPI package was uploaded three times; downstream pip installed the wrong build. Approach: forbid duplicates in the package registry settings (by format), or set the duplicate asset retention count to 1; version numbers are uniquely generated from tags.

Common errors and fixes

denied: requested access to the resource is denied (docker push)

Cause: no docker login $CI_REGISTRY; the push path does not belong to this project (outside $CI_REGISTRY_IMAGE ); or the tag matches a protected container tag rule and the current user's role is insufficient.

echo "$CI_REGISTRY_IMAGE"; docker login "$CI_REGISTRY" -u "$CI_REGISTRY_USER" -p "$CI_REGISTRY_PASSWORD"
The cleanup policy is enabled, but tags have not decreased

Check:① next_run_at ① whether it is due (saving the policy resets the interval); ② whether the tag matches the keep regex (regexes are anchored automatically, so v.+ does not match 1.2.0); ③ whether it is within keep_n or newer than older_than; ④ GitLab.com has a time limit per run, so multiple rounds may be needed; ⑤ the policy is automatically disabled when the project has no images.

400 Bad Request: container_expiration_policy.keep_n is not included in the list

Cause: the parameter value is not in the allowed list (keep_n can only be 1/5/10/25/50/100, older_than only 1d…1095d, cadence only 1d/7d/14d/1month/3month). (The exact error text depends on the actual response.)

uploading a generic package returns 400 / 403

Cause: 403: the user the job token belongs to lacks permission on the project, or the package is restricted by a package protection rule; 400: the package name, version, or file name contains disallowed characters, or the project forbids duplicates and the file already exists. Diagnose:curl --fail-with-body print the response body.

Many tags deleted, storage usage unchanged

Cause: layers are referenced by other images that still have tags (deduplication within the root namespace); online garbage collection runs about 24 hours after tags are deleted; very large namespaces use a delayed calculation method. Fix: wait for one GC round, then check the usage quotas.

Command-line tasks
1. In one command, delete all tags in the myapp repository that are “8 hex digits and older than 30 days,” but keep the latest 5.
RID=$(glab api "projects/:id/registry/repositories" | jq '.[0].id')
glab api -X DELETE "projects/:id/registry/repositories/$RID/tags" \
  -f name_regex_delete='[0-9a-f]{8}' -f keep_n=5 -f older_than=30d
2. Upload dist/report.html to the generic package reports, with the version taken from the pipeline ID.
curl --fail-with-body --header "JOB-TOKEN: $CI_JOB_TOKEN" --upload-file dist/report.html \
  "$CI_API_V4_URL/projects/$CI_PROJECT_ID/packages/generic/reports/$CI_PIPELINE_ID/report.html"
Scenario analysis
Policy: keep_n=1, keep production-.*, delete tags older than 7 days, delete .*. Tags: latest(2h), production-v42(11d), dev-v44(2d), dev-v42(10d), v44(1d), v43(12d). Which will be deleted?

Kept: latest (always), production-v42 (keep regex), v44 (the newest 1). Of the remaining dev-v44, dev-v42, and v43: dev-v44 is only 2 days old (newer than 7 days) and is kept; dev-v42 and v43 are deleted. This is exactly the official example's reasoning: a match on any keep rule keeps a tag, and a delete rule must match all of its criteria to delete.

Verified instructional videos

No verified video specifically covering GitLab container registry cleanup policies or protected container tags was found; use the storyboard below. Possibly useful general videos:

▶
GitLab CI CD automation (Docker, Kubernetes, Terraform, and more…) — Christian Lempa
English · general workflow for building and pushing images in GitLab CI

Official docs

Video storyboard script (about 60 seconds)

This courseware cannot directly generate video/MP3; the storyboard and narration below can be handed to a video tool.

Shot 1 · 0–20s
Visual: tags pile up like cards in the image registry; the storage bar gradually turns red.
Narration: each commit pushes an image; after a year, the image registry fills the namespace's storage quota.
Shot 2 · 20–45s
Visual: a ten-step funnel animation: latest is picked out; tags matching the keep regex turn green; the newest ten turn green; too-new ones turn green; the rest fall into the trash.
Narration: a cleanup policy checks keep rules first; if any matches, the tag is kept; delete rules must all match before a tag is deleted.
Shot 3 · 45–60s
Visual: the 1.2.0 tag gets a lock icon, and a Developer's push is bounced back.
Narration: protected container tags restrict who can push and delete version tags; cleanup policies also skip them.
or score ≥ 70% in the quiz

Module 5 · Deployment strategies: progressive rollout, Feature Flags, and Review Apps

28:00 – 35:00 · Deploy ≠ release: first let new code “turn on” for a small amount of traffic or a few users, then decide whether to roll it out fully
7 minReview Apps · progressive rollout · Feature Flags: FreeFree allows 50 flags per project★★★★
Learning goals
  • Create a Review App for each MR: dynamic environment name review/$CI_COMMIT_REF_SLUG,environment:url,on_stop , stop job auto_stop_in, and know how the stop job is triggered when the MR is merged or the branch is deleted.
  • Following GitLab's progressive rollout pattern, write manual (when: manual) and scheduled (when: delayed + start_in) 10% / 50% / 100% jobs, and map them to actual platforms (Kubernetes replicas, Container Apps revision weights).
  • Use GitLab Feature Flags (Unleash-compatible API) to create flags and strategies (All users, Percent rollout, User IDs, User List), and read the flags in myapp.
  • Choose strategies for different risks: Review App (before merge) → progressive rollout (at deploy time) → Feature Flag (after release, per user).
Prerequisites: Lesson 3 environments, revision weights, and deployment jobs. Importance:★★★★

What: three ways to reduce release risk

Review AppsIncremental rolloutsFeature Flags
Controlsone temporary environment per branch / MRwhat proportion of instances / traffic runs the new versionwhich users have a feature turned on
GitLab mechanismdynamic environments + on_stop + auto_stop_ina group of ROLLOUT_PERCENTAGE jobs: manual or scheduled (default interval 5 minutes; can be triggered manually early)project-level flags + strategies + environment scope; the app fetches them via an Unleash client
Rollback methodclosing the MR stops itrun a job with a lower percentage; after reaching 100%, handle it as a “rollback deployment”turn off the flag; takes effect in seconds, no redeployment needed
TierFreeFree (built into Auto DevOps; or write your own)Free (.com: 50 per project; Premium 150; Ultimate 200)

How: the environment lifecycle of a Review App

  • Deployment job: environment: {name: review/$CI_COMMIT_REF_SLUG, url: …, on_stop: stop_review, auto_stop_in: 2 days}. CI_ENVIRONMENT_SLUG At most 24 characters, only lowercase letters, digits, and hyphens; suitable for composing resource names.
  • Stop job: same environment name + action: stop, usually when: manual; GIT_STRATEGY: none so it can still run after the branch is deleted.
  • When the stop is triggered: manually clicking “Stop,”auto_stop_in expiry, MR merge or close, branch deletion (the stop job must be in the same pipeline as the deployment job, with consistent rules).
  • An environment must be stopped before it can be deleted; stopping does not delete your cloud resources. Resource deletion is the command you write in the stop job script.

How: the data flow of a Feature Flag

  1. In Deploy → Feature flags, create a flag (or via API POST /projects/:id/feature_flags,version: new_version_flag).
  2. For each strategy, choose the type and the environment scope (such as production,review/*): default (All users),flexibleRollout (Percent rollout: by user ID / session ID / random / automatic, 0–100%),gradualRolloutUserId (Percent of users; the official docs now recommend Percent rollout),userWithId (User IDs),gitlabUserList (User List).
  3. The “Configure” button shows API URL (https://gitlab.com/api/v4/feature_flags/unleash/<project ID>) and Instance ID; the app's Application name fills in the runtime environment name (such as production), which is used to match the environment scope.
  4. The Unleash client in the app periodically fetches flag definitions and evaluates them locally; GitLab does not receive a call for each request.

The Instance ID can only read flag definitions, but it should still be managed as configuration, not as a public constant. Setting the “minimum role for managing flags” (introduced in 19.4, feature flag off by default) can restrict who can change flags. “Search code references” requires Premium.

When: how to combine them

  • UI / interaction changes → Review App, so product and design can see the effect before merging.
  • dependency or runtime changes (new Python version, gunicorn parameters) → progressive rollout; observe error rates before expanding.
  • business features that need per-user / per-tenant canary releases or must be turned off at any time → Feature Flag; code can be “dark deployed” to production first.

Comparison with similar technologies

GitLabGitHubAzure
temporary environmentsReview Apps (dynamic environments)deployment environments + self-built workflowsContainer Apps revisions / deployment slots
flag servicebuilt-in Unleash-compatible Feature Flagsno built-in (third party)Azure App Configuration Feature Manager
Common misconceptions① “Stopping an environment deletes the app” — it only runs your stop job. ② “Feature Flags only work in Kubernetes / Auto DevOps” — any app that can use an Unleash client works. ③ “Progressive rollout is GitLab shifting traffic for you” — GitLab only orchestrates jobs; shifting traffic is done by your deployment script (kubectl scale, revision weights). ④ “A percentage flag gives a different result for the same user each time” — with sticky user-ID bucketing, the result is consistent for the same user; only random bucketing varies.

Risk control chain from MR to production

MR !6 (feat/new-ui)deploy_reviewreview/feat-new-uiauto_stop_in: 2 days merge / close MR→ stop_review (action: stop) main → production progressive rollout rollout 10%manual rollout 50%delayed 5m rollout 100%manual platform mapping: K8s old/new Deployment replica ratioor Container Apps revision weights 90/10 → 50/50 → 0/100 rollback: run a job with a lower percentageenvironment: production · resource_group: productionafter reaching 100%, use “rollback deployment” or redeploy the old version Feature Flag new_counter_ui production: Percent rollout 25%(sticky by userId)review/*: All usersUser List: beta-testers UnleashClient in myappapp_name = environment nameGET /api/v4/feature_flags/unleash/:idevaluated locally; turning it off falls back
Figure 5-1: three layers of control: before merge (Review App), at deploy time (progressive rollout), after release (Feature Flag)

Feature Flag evaluation (in the app)

GitLab flag definitionsstrategy + environment scope UnleashClient pollingInstance ID authentication · cache is_enabled(flag, ctx)ctx.userId → hash → 0–99 old / new code path< 25 → new UI
Figure 5-2: percentage bucketing by hashed user ID; the same user gets a stable result

Interactive: progressive rollout × Feature Flag simulator

On the left are 10 instances (pods or revision-weight cells); running the progressive rollout job changes the proportion of the new version. On the right are 20 users; adjust the Feature Flag percentage and strategy. The feature each user finally sees = “the request lands on a new-version instance” AND “the flag is on for that user.” The log shows the corresponding GitLab jobs and API calls.

Progressive rollout job:
Flag strategy:
instances (new version = green)
users (see new UI = green)
Initially: all instances run the old version; the flag is Percent rollout 25%.
# job and API log

Keywords and commands

Syntax / commandPurposeNotes
environment: {name: review/$CI_COMMIT_REF_SLUG, url, on_stop, auto_stop_in}dynamic environmentThe / in the environment name makes the UI group them in one folder.
environment: {name: …, action: stop} + GIT_STRATEGY: nonestop jobcan still run after the branch is deleted
when: delayed + start_in: 5 minutesscheduled jobduring the countdown, you can run it immediately or cancel it
glab api projects/:id/environments?states=availablelist environmentsPOST …/environments/:id/stop stop
glab api -X POST projects/:id/feature_flags --input ff.jsoncreate flagPUT …/feature_flags/:name modify
glab api -X POST projects/:id/feature_flags_user_listscreate user listuser_xids comma-separated

1. Review App (the full GitLab-side lifecycle; the deployment command can be replaced)

deploy_review:
  stage: deploy
  image: alpine:3.22
  rules:
    - if: $CI_PIPELINE_SOURCE == "merge_request_event"
  variables:
    REVIEW_NAME: mr-$CI_ENVIRONMENT_SLUG        # ≤ 27 characters, meets most cloud resource naming limits
  script:
    - echo "deploy $CI_REGISTRY_IMAGE:$CI_COMMIT_SHORT_SHA as $REVIEW_NAME"
    - echo "REVIEW_URL=https://$REVIEW_NAME.example.com" >> deploy.env   # write the actual URL after the real deployment
  artifacts:
    reports:
      dotenv: deploy.env
  environment:
    name: review/$CI_COMMIT_REF_SLUG
    url: $REVIEW_URL                              # can reference variables from dotenv
    on_stop: stop_review
    auto_stop_in: 2 days

stop_review:
  stage: deploy
  image: alpine:3.22
  rules:
    - if: $CI_PIPELINE_SOURCE == "merge_request_event"
      when: manual
      allow_failure: true
  variables:
    GIT_STRATEGY: none
  script:
    - echo "delete mr-$CI_ENVIRONMENT_SLUG"
  environment:
    name: review/$CI_COMMIT_REF_SLUG
    action: stop

environment:url Referencing a dotenv variable is the dynamic URL syntax GitLab supports. The stop job's rules must appear in the same pipeline as the deployment job; otherwise there is no stop job to run when the MR is merged.

2. (Optional) Deploy the Review App to lesson 3's Container Apps

deploy_review:
  extends: .azure-login                 # lesson 3's template (id_tokens + az login --federated-token)
  script:
    - az containerapp create -g rg-gitlab-lab -n "mr-$CI_ENVIRONMENT_SLUG" --environment cae-gitlab-lab
        --image "$IMAGE" --ingress external --target-port 5000 --min-replicas 0 -o none
    - echo "REVIEW_URL=https://$(az containerapp show -g rg-gitlab-lab -n mr-$CI_ENVIRONMENT_SLUG --query properties.configuration.ingress.fqdn -o tsv)" >> deploy.env

stop_review:
  extends: .azure-login
  script:
    - az containerapp delete -g rg-gitlab-lab -n "mr-$CI_ENVIRONMENT_SLUG" --yes
Identity note MR pipelines run on the source branch, and the ID token sub is …:ref_type:branch:ref:feat/new-ui, and lesson 3 only trusts main and v* Federated credentials for tags will not match. You need a separate low-privilege “review” identity plus a flexible federated credential (matching any branch), granting it permission only on the mr-* app; MRs from forks must not receive cloud credentials. Private images also require Container Apps to be able to pull registry.gitlab.com (configure registry credentials), or switch to the images imported into ACR in lesson 3.

3. Progressive rollout jobs (manual 10% → scheduled 50% → manual 100%)

.rollout:
  stage: production
  extends: .azure-login
  environment: { name: production, deployment_tier: production }
  resource_group: production
  script:
    - OLD=$(az containerapp revision list -g rg-gitlab-lab -n myapp-prod --query "[?properties.trafficWeight>\`0\` && name!='$NEW_REV'].name | [0]" -o tsv)
    - az containerapp ingress traffic set -g rg-gitlab-lab -n myapp-prod
        --revision-weight "$NEW_REV=$ROLLOUT_PERCENTAGE" "$OLD=$((100-ROLLOUT_PERCENTAGE))" -o none
    - echo "rolled out $ROLLOUT_PERCENTAGE% to $NEW_REV"

rollout 10%:
  extends: .rollout
  variables: { ROLLOUT_PERCENTAGE: 10 }
  when: manual

rollout 50%:
  extends: .rollout
  needs: ["rollout 10%"]
  variables: { ROLLOUT_PERCENTAGE: 50 }
  when: delayed
  start_in: 5 minutes

rollout 100%:
  extends: .rollout
  needs: ["rollout 50%"]
  variables: { ROLLOUT_PERCENTAGE: 100 }
  when: manual

This is the official progressive rollout example (ROLLOUT_PERCENTAGE + manual / scheduled templates) rewritten for Container Apps revision weights; NEW_REV is passed in via dotenv from the previous deployment job. At 100%, OLD=0, Container Apps keeps revisions with weight 0 so you can switch back. On Kubernetes, adjust the replica counts of the old and new Deployments instead (Auto DevOps has this logic built in).

4. Feature Flag: create the flag and user list

cat > ff.json <<'EOF'
{ "name": "new_counter_ui", "version": "new_version_flag", "description": "New counter page",
  "strategies": [
    { "name": "flexibleRollout", "parameters": { "groupId": "new_counter_ui", "rollout": "25", "stickiness": "default" },
      "scopes": [ { "environment_scope": "production" } ] },
    { "name": "default", "parameters": {}, "scopes": [ { "environment_scope": "review/*" } ] }
  ] }
EOF
glab api -X POST "projects/$(enc "$GL_PROJECT")/feature_flags" --input ff.json -H "Content-Type: application/json" \
  | jq -c '{name, active, strategies: [.strategies[] | {name, parameters, env: .scopes[0].environment_scope}]}'
{"name":"new_counter_ui","active":true,"strategies":[{"name":"flexibleRollout","parameters":{"groupId":"new_counter_ui","rollout":"25","stickiness":"default"},"env":"production"},{"name":"default","parameters":{},"env":"review/*"}]}

5. Read the flag in myapp (Python Unleash client, example)

# app.py snippet: pip install UnleashClient
import os
from UnleashClient import UnleashClient

ff = UnleashClient(
    url=os.environ["UNLEASH_URL"],                 # https://gitlab.com/api/v4/feature_flags/unleash/<project ID>
    app_name=os.environ.get("APP_ENV", "production"),
    instance_id=os.environ["UNLEASH_INSTANCE_ID"],
    disable_metrics=True, disable_registration=True,
)
ff.initialize_client()

@app.route("/")
def index():
    hits = redis_hits()
    user = request.headers.get("X-User-Id", "anonymous")
    if ff.is_enabled("new_counter_ui", {"userId": user}):
        return f"<h1>✨ Visit #{hits}</h1>"
    return f"Hello! hits={hits}"

Parameter names follow the docs for the UnleashClient version in use; metrics and registration are disabled because GitLab's Unleash-compatible API is only used to read flag definitions. /healthz is not affected by the flag.

Lab 5: Review App lifecycle + 25% Feature Flag (about 12 min, zero cloud cost)

1. Add deploy_review / stop_review (Commands tab, part 1) and in stages add deploy,production:
cd ~/gitlablab/myapp && git switch main && git pull && git switch -c feat/new-ui
glab ci lint && git commit -am "ci: review apps

Changelog: added" && git push -u origin HEAD
glab mr create -t "feat: new counter UI" -d "review app demo" -y
glab ci status --wait
glab api "projects/:id/environments?states=available" | jq -r '.[] | "\(.name)  \(.external_url)  auto_stop_at=\(.auto_stop_at)"'
review/feat-new-ui  https://mr-review-feat-new-u-x1y2z3.example.com  auto_stop_at=2026-11-18T10:20:31Z

The MR page shows a “View app” button and an environment card. CI_ENVIRONMENT_SLUG will be truncated, and a random suffix is appended to ensure uniqueness (example value).

2. Three ways to stop an environment: in the MR, click “Stop environment”; or glab api -X POST "projects/:id/environments/<ID>/stop"; or close or merge the MR. Afterwards, stop_review job log shows delete mr-…, the environment status changes to stopped; it can be deleted under Operate → Environments.
3. Create the Feature Flag (Commands tab, part 4); in Deploy → Feature flags → Configure, note the API URL and the Instance ID.
4. Verify percentages and stickiness locally
python3 -m venv ~/gitlablab/ffvenv && . ~/gitlablab/ffvenv/bin/activate && pip install -q UnleashClient
export UNLEASH_URL="https://gitlab.com/api/v4/feature_flags/unleash/$(glab api "projects/$(enc "$GL_PROJECT")" | jq .id)"
export UNLEASH_INSTANCE_ID=<copied from the Configure dialog>
python3 - <<'EOF'
import os, time
from UnleashClient import UnleashClient
c = UnleashClient(url=os.environ["UNLEASH_URL"], app_name="production",
                  instance_id=os.environ["UNLEASH_INSTANCE_ID"], disable_metrics=True, disable_registration=True)
c.initialize_client(); time.sleep(2)
on = [u for u in range(1000) if c.is_enabled("new_counter_ui", {"userId": str(u)})]
print(f"enabled for {len(on)}/1000 users; user 7 ->", c.is_enabled("new_counter_ui", {"userId": "7"}))
c.destroy()
EOF
enabled for 247/1000 users; user 7 -> False

Run it several times; the result for the same user stays the same (sticky by userId); change app_name to review/feat-new-ui, and all users become True (environment scope of the All users strategy review/*). Turn the flag off in the UI; within a few seconds to one polling interval, everyone becomes False. No redeployment needed.

5. Cleanup: close the MR (which triggers stop), delete the flag glab api -X DELETE "projects/:id/feature_flags/new_counter_ui", or keep it for the unified cleanup in Module 8.
Verify In Operate → Environments, the review/ folder appears and disappears after stopping; the Feature flags page shows the two strategies and their environment scopes.

Case 1: a Review App blew up the cloud bill

Problem: One Review App per MR, and nobody stopped them; after three months, 140 container apps had accumulated. Approach:auto_stop_in: 2 days; the stop job actually deletes resources; set --min-replicas 0; a scheduled task calls the environments API to list environments older than 7 days review/* and stops them; use resource tags gitlab-env=… for cost allocation.

Case 2: a memory leak found during progressive rollout

Problem: After upgrading gunicorn, memory kept rising during the 10% traffic stage. Approach: The on-call engineer cancelled the scheduled 50% job (it can be cancelled during the countdown) and manually ran the “back to 0%” job; after the problem was fixed, the release was redeployed. Key point: Scheduled jobs give an observation window, and resource_group prevent two releases from adjusting weights at the same time.

Case 3: flag debt

Problem: A year later the project had 48 flags (Free limit 50), many already at 100% rollout, while the code still contained both paths. Approach: When creating a flag, open an Issue that records the cleanup date; two weeks after full rollout, delete the old path and the flag (Premium can use “search code references”); include the “flag count” on the tech debt dashboard.

Common errors and fixes

The Review App environment was not stopped after the MR was merged

Cause: The rules of the stop job and the deploy job are inconsistent, so the stop job does not appear in the same pipeline; on_stop the environment name is misspelled; the stop job needs to check out code, but the branch has already been deleted. Fix: use the same rules for both, and the stop job when: manual + GIT_STRATEGY: none.

jobs:stop_review:environment action stop requires a name (or environment name can contain only letters…)

Cause: the environment name contains disallowed characters, or a variable expands to an empty value. Fix: use $CI_COMMIT_REF_SLUG / $CI_ENVIRONMENT_SLUG; in the job echo "$CI_ENVIRONMENT_NAME" to confirm. (Follow the actual error text.)

The Unleash client always returns False

Check:① app_name ① whether it matches the environment scope of the strategy (production vs prod); ② whether the flag is active; ③ whether the project ID in the API URL corresponds to the Instance ID; ④ percentage strategies need userId in the context (Percent of users / sticky by user); ⑤ whether the client has finished its first fetch (there is a brief delay after initialization).

Feature flag limit reached / cannot create more flags

Cause: GitLab.com Free allows at most 50 per project (Premium 150, Ultimate 200; self-managed defaults to 200). Fix: delete flags that are already fully rolled out.

scheduled job rollout 50% runs immediately or never runs

Cause:start_in wrong format (needs something like 5 minutes,1 hour, up to one week); needs the preceding manual job it points to has not run, so the scheduled job does not start its countdown.

Command-line tasks
1. List all review environments that have not been updated for more than 7 days and are still available, and stop them.
CUT=$(date -u -d '7 days ago' +%FT%TZ)
glab api "projects/:id/environments?states=available&search=review/" \
  | jq -r --arg c "$CUT" '.[] | select(.updated_at < $c) | .id' \
  | xargs -r -I{} glab api -X POST "projects/:id/environments/{}/stop"
2. Change the production percentage of the new_counter_ui flag to 50%.
glab api "projects/:id/feature_flags/new_counter_ui" | jq '.strategies[] | {id, name, parameters}'
# Use PUT to update the corresponding strategy (the strategy id is required), example:
glab api -X PUT "projects/:id/feature_flags/new_counter_ui" -H "Content-Type: application/json" \
  --input <(echo '{"strategies":[{"id":36,"name":"flexibleRollout","parameters":{"groupId":"new_counter_ui","rollout":"50","stickiness":"default"}}]}')
Scenario analysis
Product requires “the new checkout flow goes first to internal employees, then to 5% of external users, and is turned off within 1 minute if something goes wrong,” while operations requires “the new image runs first on 10% of instances for 30 minutes.” How do you combine them?

Two independent layers. The deployment layer uses progressive rollout (10% manual → 30-minute scheduled → 100%), watching error rates and resources. The feature layer uses a Feature Flag: User List (employee IDs) + Percent rollout 5% (sticky by userId), with environment scope production. After the new image reaches 100%, the feature stays off by default (dark deployment); turning off the flag rolls back the feature without rolling back the image. Both layers are written to the environment and audit logs.

Verified instructional videos

▶
Eliminating risk with feature flags — GitLab
English · GitLab official: reducing release risk with Feature Flags
▶
Demo: Cloud Native Development with GitLab — GitLab
English · early official demo, including Review Apps (older interface)

Official docs

Video storyboard script (about 60 seconds)

This courseware cannot directly generate video/MP3; the storyboard and narration below can be handed to a video tool.

Shot 1 · 0–20s
Visual: next to the MR card, a temporary environment bubble pops up with a “View app” button; the bubble bursts after the MR is merged.
Narration: a Review App creates a temporary environment for each merge request, and it stops automatically after merging or expiry.
Shot 2 · 20–40s
Visual: ten instance cells gradually turn green at 10%, 50%, and 100%, with a countdown clock in the middle.
Narration: progressive rollout puts the new version onto instances in batches; scheduled jobs give you a window to observe and cancel.
Shot 3 · 40–60s
Visual: user avatars turn green as the flag slider moves; one click turns the flag off and they all turn grey.
Narration: a Feature Flag opens a feature to users; if something goes wrong, turn the flag off. No redeployment needed.
or score ≥ 70% in the quiz

Module 6 · Merge trains and merged results pipelines

35:00 – 42:00 · Each MR is green on its own, but together they break main. A merge train tests “all the changes ahead of you + you”
7 minPremium / UltimateFree alternative: semi-linear / fast-forward merges★★★★
Learning goals
  • Distinguish three kinds of MR pipelines: detached (tests the source branch), merged results (tests a temporary merge commit of “source + target”), and merge trains (tests “target + all MRs ahead + this MR”), as well as CI_MERGE_REQUEST_EVENT_TYPE 's three values.
  • Trace what happens when an MR in a merge train fails: it is removed from the train, and the later pipelines are canceled and restarted on the new combination. Understand the cost of “merge immediately” and the concurrency limit (default 20).
  • On the Free tier, use a merge method (semi-linear / fast-forward) + “pipeline must succeed” + MR pipelines to get the guarantee that “what gets merged is what was tested,” and know its cost.
Prerequisites: Lesson 1 merge methods and merge checks; lesson 2 MR pipelines and workflow:rules. Importance:★★★★

What: three kinds of MR pipelines

TypeCode testedCI_MERGE_REQUEST_EVENT_TYPETier
MR pipeline (detached)source branch HEADdetachedFree
merged results pipelineA temporary merge commit of the source and target branches (not on any branch); on conflict, it falls back to a regular MR pipelinemerged_resultPremium / Ultimate
merge train pipelinetarget branch + all MRs ahead of it in the train + this MRmerge_trainPremium / Ultimate

Why: why merged results are still not enough

A merged results pipeline only looks at “me + the current main”; it does not know that another MR is being merged at the same time. MRs A and B are each green against the main at that time, but combined they may conflict (for example, A renames a function while B adds a call to the old function name), so main gets broken even though every pipeline succeeded.

How: how merge trains work (official docs)

  1. When the train is empty, click “Merge” (or “Set to auto-merge” while the pipeline is running) to start a train; the first MR runs a merged results pipeline.
  2. When later MRs join, each pipeline tests “target + all MRs ahead + itself,” and the pipelines run in parallel.
  3. An MR is merged only after its own pipeline succeeds and all MRs ahead of it have been merged.
  4. If an MR fails, it is removed from the train; those queued behind it's pipelines are canceled and recreated on the new combination (excluding the failed MR); those ahead of it are unaffected.
  5. “Merge immediately” (skipping the train) cancels all pipelines on the train and rebuilds them all, which is very resource-intensive and should be used only for emergency fixes. The experimental feature “merge immediately without restarting the train” lets changes merge without verification (risky).
  6. Each train runs at most 20 parallel pipelines by default (adjustable since 19.0); the excess queue up, with no limit on queue length. Once an MR joins the train, new discussions will not remove it from the train.

Prerequisites: Maintainer role; the project has MR pipelines configured (workflow:rules or job rules include merge_request_event); enable merged results pipelines first, then merge trains (Settings → Merge requests → Merge options). Turning on these two options without MR pipelines configured may leave MRs stuck in a pending state.

Free-tier alternatives

OptionHowGuaranteeCost
Semi-linear merge (merge_method: rebase_merge)Allow merging only when the source branch is already based on the latest target branch (fast-forwardable), while keeping merge commitsCombined with “pipeline must succeed,” the combination being merged is exactly the one the MR pipeline testedEach time main moves forward, other MRs must rebase and rerun the pipeline (serial; busy repos get queues)
fast-forward merge (ff)Same as above, but no merge commit is produced; history is linearSame as aboveSame as above; the merge commit habit from lesson 1 has to change
Do the “merged result” yourself inside the MR pipelineIn the job, git fetch origin main && git merge --no-edit origin/main before testing.approximate merged results pipelinestill cannot sense other MRs being merged concurrently; not fully identical to a real merge commit
main pipeline + fast rollbackwhen main fails, automatically open a revert MR and notifydiscovered afterwardsmain may be briefly broken
Trial A GitLab.com Ultimate trial (per the current terms on about.gitlab.com) lets you try merge trains; after the trial ends, the setting becomes ineffective and MRs go back to the regular merge flow. Note the original settings before the lab.

When: when merge trains are worth it

  • Many MRs are merged to main every day, and they are often ready at the same time;
  • main must always be releasable (continuous deployment);
  • pipelines take a long time, so the queuing cost of the serial rebase in the semi-linear approach is too high.

Comparison with similar technologies

GitLabGitHubAzure Repos
merge queueMerge trains (Premium)Merge queue (per GitHub docs)no built-in (use branch policies + build verification)
test merged resultmerged results pipeline (Premium)pull_request events are based on the merge commit by defaultPR builds are based on the merge commit by default
Common misconceptions① “The MR pipeline tests the merged code”: on the Free tier, a detached MR pipeline tests the source branch. ② “Merge trains are serial”: pipelines run in parallel; merges happen in order. ③ “If one fails in the train, all behind it fail”: those behind it are restarted (excluding the failed MR), not failed. ④ “rules:changes:compare_to behaves the same in merged results pipelines”: the baseline is the temporary merge commit, which may trigger unexpected jobs (see official troubleshooting).

Merge train: re-ordering after B fails

t1: A, B, C join in turn (three pipelines run in parallel) main P1: main + A P2: main + A + B P3: main + A + B + C t2: P2 fails → B removed; P3 canceled and rebuilt as main + A + C P1: keeps running P2 ✗ B removed from the train P3 canceled → P3': main + A + C t3: P1 succeeds → A merged; P3' succeeds → C merged (order guaranteed) main ← A main ← C (already includes A)
Figure 6-1: the failed MR is removed; only the pipelines queued behind it need to be rebuilt

Free: the serial pace of semi-linear merges

MR A: based on latest mainpipeline ✓ → merge MR B: behind main“needs rebase” cannot merge B rebased → new pipelinetests main + B ✓ → mergemain is always tested The guarantee is the same, but serial: N MRs that are ready at the same time need about N rounds of “rebase + pipeline”; merge trains run them in parallel.
Figure 6-2: on the Free tier, “only fast-forwardable merges + pipeline must succeed” achieves the same correctness

Interactive: merge train simulator

Add MRs to the train, choose a pipeline to fail or “merge immediately,” and watch how GitLab cancels and rebuilds pipelines and when merges actually happen. Below, compare the number of rounds the same MRs need under Free semi-linear merges.

The train is empty. Click “add next MR.”
# train events

Settings and commands

Command / settingPurposeTier
glab api -X PUT projects/:id -f merge_pipelines_enabled=trueEnable merged results pipelinesPremium
glab api -X PUT projects/:id -f merge_trains_enabled=trueEnable merge trainsPremium
glab api -X PUT projects/:id -f merge_method=rebase_mergeSemi-linear merge (ff is fast-forward,merge is a regular merge commit)Free
glab mr merge 6When the train is enabled: join the train (if the pipeline is running, set auto-merge,--auto-merge default true)—
glab mr rebase 6server-side rebase of the source branch (commonly used with semi-linear / fast-forward)Free
glab api projects/:id/merge_trainsview MRs in the train and their statusPremium
glab api -X PUT projects/:id/merge_requests/:iid/merge -f skip_merge_train=trueskip the train and merge directly without restarting the train (experimental feature; must be enabled in settings)Premium

1. Make pipelines behave correctly for the three kinds of MR pipelines

workflow:
  rules:
    - if: $CI_PIPELINE_SOURCE == "merge_request_event"     # detached / merged_result / merge_train all come from this source
    - if: $CI_COMMIT_BRANCH && $CI_OPEN_MERGE_REQUESTS
      when: never
    - if: $CI_COMMIT_BRANCH
    - if: $CI_COMMIT_TAG

e2e:
  rules:
    - if: $CI_MERGE_REQUEST_EVENT_TYPE == "merge_train"   # only run the most expensive end-to-end tests on trains
    - if: $CI_COMMIT_BRANCH == $CI_DEFAULT_BRANCH

deploy_review:
  rules:
    - if: $CI_MERGE_REQUEST_EVENT_TYPE == "merge_train"   # train pipelines do not need Review Apps
      when: never
    - if: $CI_PIPELINE_SOURCE == "merge_request_event"

lesson 2's workflow:rules already satisfies the prerequisite of “MR pipelines configured.” Assigning jobs by event type makes regular MR pipelines faster and train pipelines more complete.

2. Free: switch to semi-linear merges and verify

glab api -X PUT "projects/$(enc "$GL_PROJECT")" -f merge_method=rebase_merge \
  -f only_allow_merge_if_pipeline_succeeds=true | jq '{merge_method, only_allow_merge_if_pipeline_succeeds}'
glab mr view 6 -F json | jq '{iid, detailed_merge_status, diverged_commits_count}'
glab mr rebase 6 && glab ci status --wait && glab mr merge 6 --yes
{ "merge_method": "rebase_merge", "only_allow_merge_if_pipeline_succeeds": true }
{ "iid": 6, "detailed_merge_status": "need_rebase", "diverged_commits_count": 2 }
✓ Rebase successful
(success) • 03m 10s   refs/merge-requests/6/head
✓ Merged!

3. Premium: enable merged results pipelines and merge trains

glab api -X PUT "projects/$(enc "$GL_PROJECT")" -f merge_pipelines_enabled=true -f merge_trains_enabled=true \
  | jq '{merge_pipelines_enabled, merge_trains_enabled}'
glab mr merge 7      # join the train
glab api "projects/$(enc "$GL_PROJECT")/merge_trains" | jq -r '.[] | "\(.merge_request.iid) \(.status) pipeline=\(.pipeline.id)"'
{ "merge_pipelines_enabled": true, "merge_trains_enabled": true }
7 fresh pipeline=2087654401
8 fresh pipeline=2087654402

On the Free tier, these parameters have no effect (the return value stays false or does not appear); follow the actual response.

Lab 6: Free semi-linear merge walkthrough (Premium can optionally do merge trains, about 12 min)

1. Create two MRs that are “each green, but red together”
cd ~/gitlablab/myapp && git switch main && git pull
git switch -c feat/rename && sed -i 's/def index/def home/; s/index()/home()/' app.py
git commit -am "refactor: rename index to home" && git push -u origin HEAD && glab mr create -t "refactor: rename index" -d "" -y
git switch main && git switch -c feat/test-index
cat >> tests/test_app.py <<'EOF'

def test_index_function_exists():
    import app
    assert callable(app.index)
EOF
git commit -am "test: index exists" && git push -u origin HEAD && glab mr create -t "test: index exists" -d "" -y

Both MRs' detached pipelines will pass (each is based on the old main). For the specific renaming approach, adjust according to your app.py code; the goal is to make the second MR depend on a name that the first MR deletes.

2. Old behavior (merge commit method): first merge feat/rename, then merge feat/test-index. If the merge method is still the lesson 1 merge commit and the MR pipeline is already green, the second MR can be merged directly, and the main pipeline then turns red. Do not actually leave main red: after observing, immediately revert (glab mr create one revert MR).
3. Switch to semi-linear merges (Commands tab, part 2); repeat steps 1–2. The second MR shows “needs rebase”; after rebasing, its pipeline runs on “main + this MR” and fails, and the MR is blocked from merging. The problem is caught before it enters main.
4. (Premium / trial) merge trains: restore the merge commit method, enable merged results pipelines and merge trains, add the two MRs to the train in turn, and observe the second MR's train pipeline fail and be removed while main stays green.
5. Restore settings
glab api -X PUT "projects/$(enc "$GL_PROJECT")" -f merge_method=merge \
  -f merge_trains_enabled=false -f merge_pipelines_enabled=false | jq '{merge_method}'
glab mr close 6 7 2>/dev/null; git push origin --delete feat/rename feat/test-index

You may also keep semi-linear merges as the long-term practice on the Free tier. MR numbers are examples.

Verify In semi-linear mode, when the source branch is behind, the MR merge control shows a rebase button; main's pipeline history no longer contains records of “failed after merging.”

Case 1: the “red main” of a continuous-deployment team

Problem: A 30-person team merges 40 MRs a day; main breaks 2–3 times a week, blocking all deployments for an hour each time. Approach: Upgrade to Premium and enable merged results + merge trains; run the end-to-end tests only on merge_train events; keep the default concurrency limit of 20 when resources are sufficient. Effect: main breakages drop to nearly zero; the cost is that train pipelines consume more compute minutes.

Case 2: semi-linear merges for a Free-tier team

Problem: A small team cannot buy Premium. Approach: semi-linear merges + “pipeline must succeed” + “skipped pipelines count as success” turned off; keep MR pipelines under 5 minutes to reduce rebase queuing. Limits: The more MRs ready at the same time, the longer the queue for rebases.

Case 3: abusing “merge immediately”

Problem: Developers frequently clicked “merge immediately” to hurry; each time, all 15 pipelines on the train were rebuilt, and the runners were badly backlogged. Approach: Only Maintainers have merge permission; write “merge immediately” into the incident procedure, limited to hotfixes; evaluate the risks of the experimental feature “merge immediately without restarting the train.”

Common errors and fixes

The MR keeps showing “checking if it can be merged” / is stuck in a pending state (after enabling merged results)

Cause: Merged results / trains are enabled, but .gitlab-ci.yml has no MR pipeline configured, so the pipeline is discarded. Fix: In workflow:rules , add merge_request_event (see Commands, part 1).

The merged results pipeline does not appear; the detached pipeline still runs

Cause: the source and target branches conflict (official: in this case a regular MR pipeline runs); or the project is not Premium; or the MR comes from a fork and the parent project's members have not manually run the pipeline. Diagnose: In the job echo $CI_MERGE_REQUEST_EVENT_TYPE.

MR removed from the merge train: pipeline failed / merge request is not mergeable

Cause: this MR fails its tests when combined with the MRs ahead of it, or a conflict occurs. Fix: Reproduce locally in git merge the branches of the MRs ahead; after fixing, add it back to the train.

rules:changes:compare_to triggered unexpected jobs in merged results pipelines

Cause: the comparison baseline is the temporary merge commit, which includes other changes from the target branch (official troubleshooting). Fix: remove compare_to or narrow the path patterns.

A failed branch pipeline was “overridden” by a successful merged results pipeline, and the MR can still be merged

Cause: when “pipeline must succeed” is enabled, the system looks at the latest MR-related pipeline (known issue 385841 in the official docs). Approach: understand this priority; where necessary, also set protection on branch pipelines.

Command-line tasks
1. View the project's current merge method, whether pipelines must succeed, and whether merged results and merge trains are enabled.
glab api "projects/:id" | jq '{merge_method, only_allow_merge_if_pipeline_succeeds, merge_pipelines_enabled, merge_trains_enabled}'
2. Write a job rule that runs only in merge train pipelines.
rules:
  - if: $CI_MERGE_REQUEST_EVENT_TYPE == "merge_train"
Scenario analysis
The train has A, B, C, D in order. C's pipeline fails. Which pipelines are canceled and rebuilt? What are the possible final merge orders?

C is removed from the train; A's and B's pipelines are unaffected and keep running; D's pipeline (originally main + A + B + C + D) is canceled and rebuilt as main + A + B + D. If A, B, and D all succeed, the merge order is A → B → D; after C is fixed, it rejoins the train at the back of the queue.

Verified instructional videos

▶
How to avoid broken master with Merge Train — GitLab Unfiltered
English · official docs reference: how parallel execution in merge trains prevents breaking the default branch

Official docs

Video storyboard script (about 60 seconds)

This courseware cannot directly generate video/MP3; the storyboard and narration below can be handed to a video tool.

Shot 1 · 0–15s
Visual: two green MRs, A and B, merge at the same time, and main turns red.
Narration: each of the two MRs passes its tests, but together they may break main.
Shot 2 · 15–45s
Visual: train cars attach A, then A+B, then A+B+C, with three pipelines running in parallel; the B car turns red and detaches, and the C car reconnects behind A.
Narration: a merge train has each MR test all the changes ahead of it plus itself; if one fails, it is removed, and the ones behind it are tested again.
Shot 3 · 45–60s
Visual: under the Free badge, the MR shows a “needs rebase” button; after rebasing, the pipeline runs again.
Narration: the Free tier can use semi-linear or fast-forward merges with “pipeline must succeed,” at the cost of serial rebases.
or score ≥ 70% in the quiz

Module 7 · Infrastructure as code: GitLab-managed Terraform state

42:00 – 50:00 · State files live in GitLab: HTTP backend + GitLab permissions + locking + versions + encryption at rest; the pipeline uses the official OpenTofu component
8 minFreeOpenTofu component 5.1.0 · tofu 1.13.9Terraform templates were removed in 18.0★★★★
Learning goals
  • Explain how GitLab-managed state works: the OpenTofu / Terraform http backend → /api/v4/projects/:id/terraform/state/:name (GET / POST for read and write; /lock POST / DELETE for lock and unlock); the state carries a version (serial) and is encrypted at rest with the instance key.
  • Use gitlab.com/components/opentofu/validate-plan-apply@5.1.0 to build a fmt → validate → plan → manual apply pipeline, and understand state_name,root_dir,auto_define_backend,trigger_in_child_pipeline,enable_id_tokens and similar inputs.
  • Use glab opentofu init / state list / lock / unlock / delete to access the state locally, and know the role requirements (a Developer can only plan -lock=false, while locking and writing require Maintainer).
  • Know the currently recommended path: GitLab no longer provides Terraform CI/CD templates and images, and the official recommendation is the OpenTofu component. To keep using Terraform, you need to build your own image (for Terraform itself, see the Terraform course).
Prerequisites: Basic Terraform / OpenTofu commands (init / plan / apply, state, backend); Module 1 components and Module 2 child pipelines. Importance:★★★★

What: four things GitLab provides for IaC

CapabilityDescriptionTier
GitLab-managed stateeach project can have multiple named states (such as dev,prod), names may contain periods (16.0+); UI: Operate → Terraform states (view versions, locks, download, delete)Free
MR integrationThe plan job uploads a reports: terraform report; the MR widget shows “how many resources will be added / changed / destroyed”; Terraform reports from child pipelines also appear in the MR since 18.6.Free
module registryTerraform / OpenTofu module registry (a format of the package registry)Free
OpenTofu CI/CD componentgitlab.com/components/opentofu: full-pipeline,validate-plan-apply,validate-plan,validate-plan-destroy,job-templates , and single-job components; the image includes a gitlab-tofu wrapper scriptFree

How: what the HTTP backend does during an apply

  1. gitlab-tofu init automatically configured from CI variables http backend: address $CI_API_V4_URL/projects/$CI_PROJECT_ID/terraform/state/$GITLAB_TOFU_STATE_NAME, lock address …/lock, authentication uses the job token (username gitlab-ci-token). It is recommended to use environment variables instead of -backend-config, otherwise the configuration will be cached into the plan file, causing lock problems during apply (official docs).
  2. plan: POST …/lock acquire lock → GET read latest state → refresh and compute the diff → write out plan.cache and plan.json (artifacts) → DELETE …/lock release the lock.
  3. apply (manual job): re-lock, run the same plan file,POST and write the new state (serial + 1; GitLab saves it as a new version), then release the lock.
  4. Another pipeline requests a lock while it is held → HTTP 409 Conflict → tofu reports “Error acquiring the state lock” and shows the holder's info (ID, operation, job).
Two security points (official docs)① State files are encrypted at rest (Lockbox, with the key derived from the instance's db_key_base). If the GitLab instance is unavailable, you cannot read the state either; do not keep the state of “infrastructure GitLab itself depends on” only on this GitLab. ② plan.json / plan.cache Not encrypted, may contain passwords and tokens, and by default even Guests can download artifacts: set artifacts:access: developer (component input plan_artifacts_access, default none), keep the project private and turn off public pipelines, or enable OpenTofu's state and plan encryption (component auto_encryption).

Roles and permissions

OperationMinimum role
tofu plan -lock=false (read-only)Developer (component input allow_developer_role_to_plan: true automatically adds -lock=false)
lock, unlock, write (apply)Maintainer
access locally (glab opentofu init)personal access token; fine-grained tokens need Terraform State Read / Create / Lock permissions

A CI job token represents the triggering user: when an MR pipeline is triggered by a Developer, it cannot acquire locks, so plan needs -lock=false; apply runs manually on main by a Maintainer only, consistent with the design of protected branches and protected environments (Premium).

When: when to use GitLab-managed state

  • The team already manages code and permissions on GitLab, and does not want to maintain an S3 + locking or Azure Storage backend and its credentials.
  • You need a version record of “who changed the state and when,” and want to control read and write with GitLab roles.
  • Not suitable for: the infrastructure where GitLab itself runs (bootstrap problem); scenarios where state must be shared across multiple SaaS platforms and you do not want to depend on GitLab availability.

Comparison with similar technologies

GitLab-managed stateS3 backend (use_lockfile)azurerm backendHCP Terraform
lockHTTP /lockS3 native lock fileBlob leaseworkspace lock
authenticationGitLab token / job tokenAWS credentialsAzure credentialsHCP token
version historybuilt-inS3 versioningBlob versions / snapshotsbuilt-in
Seethis lessonTerraform 8-hour course(backends, state internals, team collaboration)
Common misconceptions① “GitLab still provides Terraform.gitlab-ci.yml templates” — these were announced as deprecated in 16.9 and removed in 18.0; migration rules: Terraform.gitlab-ci.yml → validate-plan-apply,Terraform/Base → job-templates (.terraform: prefix changed to .opentofu:). ② “Components can only run OpenTofu”: the official docs say they “may” run Terraform, but this is not officially supported; you need your own image containing gitlab-tofu compatible script image. ③ “Encrypting state makes plan artifacts safe too”: plan artifacts are not encrypted. ④ “A Developer can apply”: locked writes require Maintainer.

OpenTofu component pipeline and GitLab-managed state

mygroup-lab/platform/infra · include: opentofu/validate-plan-apply@5.1.0 fmt validate planplan.cache / json apply (main · manual)environment = state_name MR: plan (-lock=false optional) + reports:terraform → the MR widget shows changesresource_group = state_name: jobs for the same state run serially GitLab-managed state API GET /terraform/state/dev read POST /terraform/state/dev write (new version) POST /terraform/state/dev/lock lock DELETE …/dev/lock unlock 409 Conflict already locked Versions: serial 1 · 2 · 3 … (downloadable) Encryption at rest: Lockbox (db_key_base) Permissions: Developer reads; Maintainer locks / writes Locally: glab opentofu init dev UI: Operate → Terraform states plan artifacts are not encryptedplan_artifacts_access: none (default in 5.1.0)or developer; project privateor auto_encryption: true
Figure 7-1: the component handles job orchestration; gitlab-tofu points the http backend at the GitLab state API

Multiple environments: one child pipeline per state

parent pipelinetwo include:component uses child: opentofu-devstate_name: dev · root_dir: envs/dev child: opentofu-prodstate_name: prod · root_dir: envs/prod trigger_in_child_pipeline: truedistinguished by child_pipeline_nameeach environment has its own state and lock
Figure 7-2: the component input trigger_in_child_pipeline puts the whole set of jobs into a child pipeline (Module 2)

Interactive: state locks and versions (two pipelines competing for the same state)

Pipeline A (main, Maintainer) and pipeline B (another MR / manual rerun) operate on the same state at the same time dev. Click the buttons to advance with real HTTP calls, and observe the locks, 409 conflicts, version numbers, and the risks of forced unlocking.

Lock
unlocked
State version (serial)
Resources
Click “A: plan” to start.
# HTTP calls and tofu output

Commands at a glance

CommandPurposeNotes
glab opentofu init devInitialize the current directory against the GitLab state locally devglab ≥ 1.66 (GitLab 18.3+); -d directory,-b terraform uses the Terraform binary; -- -migrate-state passthrough arguments
glab opentofu state listlist the project's states-F json
glab opentofu state lock|unlock devmanually lock / unlockconfirm no job is running before unlocking
glab opentofu state delete dev [serial]delete an entire state or a specific version--force skip the confirmation
gitlab-tofu plan / applywrapper script in the component imageGITLAB_TOFU_STATE_NAME,GITLAB_TOFU_ROOT_DIR and similar variables
tofu init -backend-config=address=… -backend-config=lock_address=…/lock …Manual init without glablock_method=POST,unlock_method=DELETE,retry_wait_min=5

1. infra project: zero-cost OpenTofu configuration

# main.tf — uses only random and the built-in terraform_data, and creates no cloud resources
terraform {
  required_providers {
    random = { source = "hashicorp/random", version = "~> 3.7" }
  }
}

variable "env" { type = string }

resource "random_pet" "app" {
  prefix = "myapp-${var.env}"
  length = 2
}

resource "terraform_data" "release" {
  input = { app = random_pet.app.id, image_tag = "1.2.0" }
}

output "app_name" { value = random_pet.app.id }

Do not write backend "http" {}, leave it to the component input auto_define_backend: true to generate automatically; if you write it by hand, keep the empty backend "http" {} block. hashicorp/random The version constraint is an example; use the Registry as the reference.

2. infra project's .gitlab-ci.yml

include:
  - component: $CI_SERVER_FQDN/components/opentofu/validate-plan-apply@5.1.0
    inputs:
      version: 5.1.0                    # the component requirement must match the include version (explained in the component)
      opentofu_version: 1.13.9
      root_dir: envs/dev
      state_name: dev
      auto_define_backend: true
      allow_developer_role_to_plan: true
      plan_artifacts_access: developer

stages: [validate, build, deploy]

variables:
  TF_VAR_env: dev

The component's default apply_rules is “manual run on the default branch”; plan_rules runs by default in MR pipelines (or in branch pipelines when there is no MR). version The input is kept by the component for compatibility with older GitLab versions (component context only became GA in 18.7); keeping it consistent with @5.1.0 is enough.

3. Access the same state locally

cd ~/gitlablab/infra/envs/dev
glab opentofu init dev -R "$INFRA_PROJECT"
tofu state list
glab opentofu state list -R "$INFRA_PROJECT"
Initializing the backend...
Successfully configured the backend "http"! OpenTofu will automatically
use this backend unless the backend configuration changes.
OpenTofu has been successfully initialized!
random_pet.app
terraform_data.release
NAME   LATEST VERSION   LOCKED   UPDATED
dev    3                false    2026-11-16 10:42

4. Manual init without glab (migration or tools outside CI)

PROJECT_ID=$(glab api "projects/$(enc "$INFRA_PROJECT")" | jq .id)
TF_ADDRESS="https://gitlab.com/api/v4/projects/${PROJECT_ID}/terraform/state/dev"
tofu init \
  -backend-config=address=${TF_ADDRESS} \
  -backend-config=lock_address=${TF_ADDRESS}/lock \
  -backend-config=unlock_address=${TF_ADDRESS}/lock \
  -backend-config=username=${GL_USER} \
  -backend-config=password=${GITLAB_PAT} \
  -backend-config=lock_method=POST \
  -backend-config=unlock_method=DELETE \
  -backend-config=retry_wait_min=5

GITLAB_PAT Use a personal access token with api scope (or a fine-grained token). Put the token in the environment variable TF_HTTP_PASSWORD to keep it out of shell history.

5. (Optional) Deploy to Azure: component + lesson 3's OIDC

include:
  - component: $CI_SERVER_FQDN/components/opentofu/validate-plan-apply@5.1.0
    inputs:
      version: 5.1.0
      opentofu_version: 1.13.9
      state_name: azure-dev
      auto_define_backend: true
      enable_id_tokens: true            # the component uses .gitlab-tofu:id_tokens as the base job instead

.gitlab-tofu:id_tokens:
  id_tokens:
    GITLAB_OIDC_TOKEN:
      aud: api://AzureADTokenExchange   # matches the federated credential from lesson 3
# .gitlab/ci/setup-id-tokens.sh — the component sources this script at the start of the job (the input id_tokens_setup_script can change the path)
export ARM_USE_OIDC=true
export ARM_OIDC_TOKEN="$GITLAB_OIDC_TOKEN"
export ARM_CLIENT_ID="$AZURE_CLIENT_ID" ARM_TENANT_ID="$AZURE_TENANT_ID" ARM_SUBSCRIPTION_ID="$AZURE_SUBSCRIPTION_ID"

the azurerm provider reads ARM_OIDC_TOKEN to perform workload identity federation (per the provider docs). The official README uses the same script mechanism to demonstrate AWS assume-role-with-web-identity; in the base job, the official docs recommend keeping only id_tokens related keywords. The MR plan runs on the source branch, so its sub does not match the one that only trusts main federated credentials; either plan only on main, or create a read-only identity for plan.

Lab 7: plan → apply → lock conflict → version review (about 15 min, zero cost)

1. Push the infra project
cd ~/gitlablab/infra && mkdir -p envs/dev
# Save part 1 of the Commands tab as envs/dev/main.tf and part 2 as .gitlab-ci.yml
echo ".terraform/" > .gitignore
git add -A && git commit -m "feat: dev state with opentofu component" && git push -u origin main
glab ci status --wait
(manual) • 01m 30s   main
┌ validate ─ ✓ fmt  ✓ validate
├ build ──── ✓ plan
└ deploy ─── ▶ apply (manual)

Commit .terraform.lock.hcl is the recommended practice (component docs “Lockfile Handling”); if it does not exist the first time, you can first generate it locally tofu init and then commit it.

2. Review the plan and apply it manually
glab ci trace plan | grep -E 'Plan:|will be created'
glab api -X POST "projects/$(enc "$INFRA_PROJECT")/jobs/$(glab ci get -b main -F json | jq '.jobs[] | select(.name=="apply") | .id')/play" | jq -r .status
glab ci trace apply | tail -5
  # random_pet.app will be created
  # terraform_data.release will be created
Plan: 2 to add, 0 to change, 0 to destroy.
pending
Apply complete! Resources: 2 added, 0 changed, 0 destroyed.
Outputs:
app_name = "myapp-dev-quick-otter"

You can also click the apply ▶ directly on the pipeline page. glab ci get Output fields depend on the glab version used.

3. Create a lock conflict: locally glab opentofu state lock dev -R "$INFRA_PROJECT", then run a new pipeline on main in GitLab: the plan job fails, and the log shows Error acquiring the state lock and 409. glab opentofu state unlock dev -R "$INFRA_PROJECT" After the lock is released, retry the plan and it succeeds.
4. Versions and review: change image_tag to 1.3.0 and apply once more; in Operate → Terraform states → dev, versions 1, 2… are shown;
glab opentofu state list -R "$INFRA_PROJECT" -F json | jq '.[] | {name, latestVersion: .latest_version.serial?}'
glab api "projects/$(enc "$INFRA_PROJECT")/terraform/state/dev/versions/1" | jq '.serial, (.resources | length)'

With a PAT-authenticated glab api you can directly read the state JSON of a specific version (note that it may contain sensitive values). Field names follow the actual output.

5. Plan report in the MR: on a branch, change length = 2 to 3 and open an MR. The MR page shows “1 to add, 0 to change, 1 to destroy” (random_pet is replaced); Developers can also see the plan, while apply can still only be run by a Maintainer on main.
Verify In Operate → Terraform states, dev shows the latest version, the job link, and “unlocked”; tofu output the local and CI results match.

Case 1: migrating from Terraform templates

Problem: After upgrading to GitLab 18,include: template: Terraform.gitlab-ci.yml 's pipelines all reported “template not found.”Approach: Following the migration rules in the component README, change to validate-plan-apply@5.1.0, and turn variables into inputs (TF_ROOT → root_dir,TF_STATE_NAME → state_name). The state does not need migration (same GitLab state API). Teams that keep using Terraform clone gitlab-org/terraform-images and maintain their own image.

Case 2: a plan artifact leaked the database password

Problem: The MR pipeline artifact of a public project plan.json contains the RDS master password in plain text. Approach: Change the password to ephemeral / generated by a secrets service, so it does not enter the state plan_artifacts_access: none; enable auto_encryption; make the project private, turn off public pipelines, and rotate the password.

Case 3: a job was canceled and the state stayed locked

Problem: The runner was reclaimed midway through apply; the lock was not released; the next day all plans failed. Approach: After confirming no job is running, glab opentofu state unlock prod (or unlock in the UI); check whether the latest state version is complete, and restore it from the previous version if necessary; the component's default resource_group ensures jobs for the same state run serially, reducing concurrent writes.

Common errors and fixes

Error acquiring the state lock … HTTP remote state endpoint invalid auth / 409 Conflict

Cause: the state is locked by another job or a local session (409); or the user represented by the job token is only a Developer (cannot lock). Fix: wait or confirm and then unlock; for a Developer's plan, use allow_developer_role_to_plan: true (-lock=false); apply is run by a Maintainer.

glab opentofu state list -R "$INFRA_PROJECT"
glab opentofu state unlock dev -R "$INFRA_PROJECT"
Can't lock Terraform state files in CI jobs for terraform apply with a previous job's plan

Cause: The plan was run with -backend-config=…, the configuration was cached into the plan file, and apply still used the job token from the plan job (now expired). Fix: Configure the backend with TF_HTTP_* environment variables (gitlab-tofu does this by default); do not pass -backend-config (official troubleshooting).

Component 'gitlab.com/components/opentofu/validate-plan-apply@5.1.0' - content not found (self-managed instance)

Cause: components can only be referenced from the same instance. Fix: On a self-managed instance, mirror components/opentofu project (mirroring GitLab.com components to self-managed requires Premium), and set image_registry_base as described in the README's “Usage on self-managed.”

`opentofu_version` input: … is not in the list of allowed options

Cause: component 5.1.0 only allows 1.13.9,1.13.2,1.12.12,1.12.11 (or $OPENTOFU_VERSION). Fix: choose a version from the list, or upgrade the component version.

Error: Backend initialization required / wrong state name, plan shows that all resources need to be created

Cause:state_name a typo in root_dir or a wrong directory, so the backend points to a new, empty state. Fix:glab opentofu state list check the name; when you must rename, use glab opentofu init new-name -- -migrate-state to migrate.

Command-line tasks
1. Migrate existing local state to GitLab-managed state prod.
glab opentofu init prod -R "$INFRA_PROJECT" -- -migrate-state   # when prompted, type yes to copy the existing state
2. Run one set of component jobs for each of dev and prod in one repository, without name collisions.
include:
  - component: $CI_SERVER_FQDN/components/opentofu/validate-plan-apply@5.1.0
    inputs: { version: 5.1.0, root_dir: envs/dev, state_name: dev, trigger_in_child_pipeline: true, child_pipeline_name: tofu-dev }
  - component: $CI_SERVER_FQDN/components/opentofu/validate-plan-apply@5.1.0
    inputs: { version: 5.1.0, root_dir: envs/prod, state_name: prod, trigger_in_child_pipeline: true, child_pipeline_name: tofu-prod }
Scenario analysis
The company plans to also store the Terraform state of “the VPC, databases, and object storage where the self-managed GitLab instance runs” in this GitLab's managed state. What do you think?

Not recommended. The official disaster-recovery notes say that the state is encrypted with a key derived from the instance db_key_base (encryption), so if the instance is offline, the state cannot be read or decrypted. If this infrastructure happens to be what GitLab itself depends on, it creates a bootstrap deadlock. Keep this part of the state in an independent backend (another GitLab, S3 / Azure Storage) and back up modules and dependencies separately.

Verified instructional videos

▶
Terraform with GitLab — GitLab Unfiltered
English · feature overview referenced by official IaC docs (recorded before the OpenTofu component; template sections are outdated)
▶
GitLab CI CD automation (Docker, Kubernetes, Terraform, and more…) — Christian Lempa
English · general approach to running Terraform in GitLab CI

Official docs

Video storyboard script (about 60 seconds)

This courseware cannot directly generate video/MP3; the storyboard and narration below can be handed to a video tool.

Shot 1 · 0–20s
Visual: the tofu icon sends four arrows to GitLab: POST lock, GET state, POST state, DELETE lock; the state version number jumps from 1 to 2.
Narration: GitLab-managed state is an HTTP backend with locking and versioning, and permissions follow GitLab roles.
Shot 2 · 20–40s
Visual: the plan of a second pipeline hits a red lock and a 409 pops up.
Narration: the same state can have only one writer at a time; the other gets a 409 and must retry after the lock is released.
Shot 3 · 40–60s
Visual: the old Terraform template card is crossed out and replaced with the OpenTofu component 5.1.0 card.
Narration: GitLab has removed the Terraform templates, and the official recommendation is the OpenTofu CI/CD component.
or score ≥ 70% in the quiz

Module 8 · Recap of the first five hours, self-test, and cleanup

50:00 – 60:00 · Link the five lessons into one delivery chain, self-assess with the readiness check script, then clean up what this lesson created in dependency order
10 minFreegitlab_ready.py → 25 checks★★★★
Learning goals
  • Use one diagram to explain how the objects from lessons 1–5 connect: groups / projects / protection rules → pipelines and runners → OIDC cloud deployment → components, downstream pipelines, Releases, registry governance, progressive delivery, and IaC.
  • Add lesson 5's 6 checks to gitlab_ready.py (25 checks in total) and locate the failed items.
  • Clean up in the order of “stop billing / stop writes first, then delete dependent objects, and finally delete shared assets,” and know which things should be kept for lesson 6.
  • Use the interactive troubleshooting tree to locate common failures in this lesson.
Prerequisites: Modules 1–7. Importance:★★★★

Five-hour knowledge map

LessonTopicCore objects / keywordsRole in lesson 5
Lesson 1Platform basicsgroups mygroup-lab / sub-groups platform, roles, protected branches and tags, MRs, approvals, merge methodscomponent projects inherit members; protected tags decide who can publish components and Releases; merge methods are the Free alternative in Module 6
Lesson 2CI/CD basics.gitlab-ci.yml,workflow:rules,needs, include, Runner,v1.0jobs replaced by components; MR pipelines are the prerequisite for merge trains; v1.0 backfill Release
Lesson 3Azureid_tokens, federated credentials, Container Apps revision weights, environmentsprogressive rollout, Review Apps, and the optional Azure fragment for OpenTofu
Lesson 4AWSSTS, ECR immutable tags, ECS circuit breaker, multi-account“deploy by digest / version” complements Module 4's cleanup policies
Lesson 5Production-grade CI/CDcomponents / Catalog, trigger / strategy, Release / changelog, registry governance, Review Apps / progressive rollout / Feature Flags, merge trains, managed state——

The eight key conclusions of this lesson

  1. Component = spec:inputs interface + semantic version + Catalog; inputs are validated when the configuration is fetched, earlier and stricter than variables.
  2. Catalog versions can only be created by the CI release keyword; @1,~latest only match published versions.
  3. trigger jobs do not use a runner; without strategy , downstream failures do not flow back; for new pipelines use mirror (18.2+),depend has two inconsistent scenarios.
  4. Child pipelines: same project, same SHA,parent_pipeline, up to two levels; multi-project: depends on the triggering user's permissions in the downstream project.
  5. Release ≠ tag; the release keyword is now implemented on top of glab; release-cli will be removed in 20.0; changelogs rely on trailers, which require vX.Y.Z tags.
  6. Cleanup policies: a match on any keep rule keeps the tag, and a delete rule must match all criteria to delete; latest is always kept; protected and immutable tags are skipped.
  7. Review App stops are performed by the stop job you write; progressive rollout is orchestrated by GitLab and executed by the platform; Feature Flags decouple release from deployment.
  8. Merge trains (Premium) test “all ahead + me”; Free uses semi-linear / fast-forward + pipeline must succeed. Managed state is an HTTP backend with locks and versions; plan artifacts are not encrypted.

Principles of cleanup order

OrderObjectWhy
1stop review environments, cancel running pipelines, unlock statestop what is still writing first
2(if created) cloud resources: tofu destroy or delete mr-* container appsstop billing; destroy only knows what to delete while the state still exists
3delete managed state, Feature Flags, deployment freezesdependencies are already gone
4restore merge methods, turn off trial feature settingsavoid affecting later lessons
5decide what to keep: component projects and Catalog, v1.0 / v1.2.0 Releases, cleanup policies, protected container tagsrecommended to keep, lesson 6 adds security scanning components on top of it
Common misconceptions① “Deleting the project cleans everything up”: cloud resources described in the managed state are not deleted; first destroy. ② “Stopping an environment deletes the container app”: it only runs the stop job. ③ “Removing a Catalog publication deletes the project”: it only deletes the Catalog metadata and published versions; the project and repository are kept.

Delivery chain for lessons 1–5

Lesson 1 Platformgroups · roles · 2FAprotected main / tagsMR · approvals · merge methods Lesson 2 CIworkflow · needsRunner lab-dockerimage :1.0 · v1.0 Lessons 3 / 4 cloudid_tokens → OIDCContainer Apps · ECSdev / prod environments Lesson 5 Production-grade CI/CD M1 component python-test@1 ← platform/ci-components M2 e2e child · per-service dynamic · deploy-config M3 Release v1.0 (backfilled) · v1.2.0 (automatic) M4 cleanup policies · protected container tags · generic package M5 review/* · rollout 10/50/100 · flag 25% M6 semi-linear merge (Free) / merge trains (Premium) M7 platform/infra · state dev · tofu 1.13.9 → Lesson 6: security scanning, SBOM, signing, policies (reuses the component project and Release flow) Invariants across the five lessons • main can only be merged via MR, and pipelines must succeed (lessons 1, 2) → semi-linear / trains in Module 6 • Only Maintainers can create v* tags → releases, production deployments, and component versions are all anchored on protected tags • No long-term cloud keys in CI (lessons 3, 4) → OpenTofu component enable_id_tokens • Pin versions: images by version / digest, components by version / SHA, tofu by opentofu_version
Figure 8-1: lesson 5 adds reuse, orchestration, and governance on top of the “platform + CI + cloud identity” of lessons 1–4

Cleanup dependency graph

stop review/*unlock state tofu destroy(if any cloud resources) delete stateflags · freeze window restore settingsmerge_method keepcomponents · Release
Figure 8-2: stop writes and billing first, then delete dependencies, and finally decide what to keep

Interactive: five-hour knowledge map

Click a “question”; the map highlights the lessons and objects needed, and shows the single most important command / keyword. Use it to check whether you can connect the knowledge.

Choose a question.
# key commands / keywords

Readiness check: add lesson 5's 6 items

cd ~/gitlablab && cp gitlab_ready.py gitlab_ready.py.bak5
python3 - <<'PY'
from pathlib import Path
p = Path("gitlab_ready.py")
src = p.read_text(encoding="utf-8")
block = '''
# ---- Lesson 5: production-grade CI/CD checks ----
rel = api(f"projects/{P}/releases?per_page=100") or []
envs = api(f"projects/{P}/environments?states=available&search=review/") or []
flags = api(f"projects/{P}/feature_flags?per_page=100") or []
cep = p.get("container_expiration_policy") or {}
checks += [
    ("PLAT", "CI uses the platform/ci-components component", "platform/ci-components/" in raw),
    ("PLAT", "all trigger jobs have a strategy configured", ("trigger:" not in raw) or ("strategy:" in raw)),
    ("PLAT", "a Release with a three-part version exists (vX.Y.Z)", any(r.get("tag_name", "").count(".") == 2 for r in rel)),
    ("PLAT", "container image cleanup policy is enabled", cep.get("enabled") is True),
    ("PLAT", "no leftover review/* environments", len(envs) == 0),
    ("PLAT", "Feature Flags count is below the Free limit of 50", len(flags) < 50),
]
'''
if "Lesson 5: production-grade CI/CD checks" not in src:
    src = src.replace("\nok = 0\n", block + "\nok = 0\n", 1)
    p.write_text(src, encoding="utf-8")
print("patched")
PY
python3 gitlab_ready.py "$GL_PROJECT" | tail -8
[PASS] PLAT CI uses the platform/ci-components component
[PASS] PLAT all trigger jobs have a strategy configured
[PASS] PLAT a Release with a three-part version exists (vX.Y.Z)
[PASS] PLAT container image cleanup policy is enabled
[PASS] PLAT no leftover review/* environments
[PASS] PLAT Feature Flags count is below the Free limit of 50

Score 25/25 = 100%

In the script, api(),P,p,raw, and checks come from the lesson 1 and 2 versions (the lesson 2 CI block defines raw), so this block must be inserted after the lesson 2 block.

Cleanup commands

CommandObject to clean up
glab api -X POST projects/:id/environments/:eid/stop → DELETE …/environments/:eidreview environments
glab api -X DELETE projects/:id/environments/review_apps?dry_run=falsebulk delete stopped review environments (API parameters per the docs)
glab opentofu state delete dev --force -R $INFRA_PROJECTmanaged state
glab api -X DELETE projects/:id/feature_flags/new_counter_uiflags
glab api -X DELETE projects/:id/freeze_periods/:fiddeployment freezes
glab repo delete $DEPLOY_PROJECT --yesprojects no longer needed

Lab 8: self-assessment + cleanup (about 10 min)

1. Run the readiness check (Commands tab), record the score; send any failed items back to the matching module to fix.
2. Stop and delete review environments
source ~/gitlablab/part5.env; enc() { printf %s "$1" | jq -sRr @uri; }
P=$(enc "$GL_PROJECT")
for id in $(glab api "projects/$P/environments?states=available&search=review/" | jq -r '.[].id'); do
  glab api -X POST "projects/$P/environments/$id/stop" >/dev/null && glab api -X DELETE "projects/$P/environments/$id" && echo "deleted env $id"
done
3. Infrastructure state (this lesson only has zero-cost resources, so you can delete the state directly; if you did the optional Azure fragment, first run destroy in CI or locally tofu destroy)
glab opentofu state list -R "$INFRA_PROJECT"
glab opentofu state unlock dev -R "$INFRA_PROJECT" 2>/dev/null || true
glab opentofu state delete dev --force -R "$INFRA_PROJECT"
az containerapp list -g rg-gitlab-lab --query "[?starts_with(name,'mr-')].name" -o tsv 2>/dev/null   # residual check for the optional fragment
4. Flags, freeze windows, and merge settings
glab api -X DELETE "projects/$P/feature_flags/new_counter_ui" 2>/dev/null
for f in $(glab api "projects/$P/freeze_periods" | jq -r '.[].id'); do glab api -X DELETE "projects/$P/freeze_periods/$f"; done
glab api -X PUT "projects/$P" -f merge_method=merge | jq -r .merge_method   # or keep rebase_merge
5. Decide what to keep: Keep platform/ci-components (lesson 6 will add security scanning components), myapp's Releases and cleanup policies, and protected container tags; Can be deleted platform/deploy-config,platform/infra (confirm the state is deleted before deleting):
glab repo delete "$DEPLOY_PROJECT" --yes
glab repo delete "$INFRA_PROJECT" --yes

On GitLab.com, a deleted project may first enter a “pending deletion” state and still occupy its name during the retention period; follow the prompts in the UI.

6. Final check: python3 ~/gitlablab/gitlab_ready.py "$GL_PROJECT" run it again; “no leftover review/* environments” should be PASS.
Verifyglab api "projects/$P/environments?states=available" | jq length Only long-lived environments such as dev / production remain; Operate → Terraform states is empty or the project has been deleted.

Case 1: the platform team's “golden path”

Problem: A new service takes two weeks to set up its pipelines. Approach: project template + components (test, build, scan, deploy) + deploy-config multi-project pipeline + OpenTofu component for managing infrastructure; new services are ready within a day. Metrics: Catalog usage count, MR cycle time, main failure rate, storage growth.

Case 2: billing left over from a course lab

Problem: A learner deleted the infra project, but the Azure resources described by its state were still being billed. Approach: before any action that deletes a project, tofu destroy; tag cloud resources with course=gitlab-part5 labels for easy retrieval.

Case 3: cleanup policy + Release asset links broken

Problem: Release asset links point to short-SHA images; the cleanup policy deleted them after 30 days, so the links broke. Approach: Releases should only link to version-number tags or digests; version-number tags are protected.

Interactive troubleshooting tree: common lesson 5 failures

Common errors and fixes (supplement)

Cannot delete environment: environment must be stopped first

First call /environments/:id/stop, then delete. (Follow the actual wording.)

glab repo delete: the project is still “pending deletion,” so a project with the same name cannot be re-created

caused by GitLab.com's delayed deletion policy; you can “delete immediately” in project settings (if available), or use a different name.

gitlab_ready.py reports NameError: name 'raw' is not defined

the lesson 5 block was inserted before the lesson 2 block, or the lesson 2 block was not added. Insert them in order, or re-read .gitlab-ci.yml.

Command-line tasks
1. In one command, list the names of all environments in the project whose state is available.
glab api "projects/:id/environments?states=available" | jq -r '.[].name'
2. Delete the first version of managed state dev (keep the other versions).
glab opentofu state delete dev 1 -R "$INFRA_PROJECT"
Scenario analysis
You need to set up a “production-grade” delivery chain for a new Python service within one day. Based on lessons 1–5, list the 8 things you would do.

① Put it in a mygroup-lab sub-group, inheriting roles and 2FA; ② protected main (MR only) and protected v* tags, merge checks (pipeline must succeed, discussions resolved); ③ include python-test@1 / docker-build@1 component; ④ MR pipeline + workflow:rules, use semi-linear merges on Free (merge trains on Premium); ⑤ OIDC deployment to dev (main) and prod (protected tags), by version / digest; ⑥ Release job + changelog trailers; ⑦ cleanup policies + protected container tags; ⑧ Review App (auto_stop_in) and Feature Flags; infrastructure with the OpenTofu component + managed state.

Verified instructional videos

▶
GitLab CI CD Tutorial for Beginners [Crash Course] — TechWorld with Nana
English · review of lesson 2 basics, good for revision
▶
Talk: Efficient DevSecOps workflows with reusable CI/CD components — GitLab Unfiltered
English · bridging to the next lesson: componentized DevSecOps (lesson 6 topic)

Official docs

Video storyboard script (about 60 seconds)

This courseware cannot directly generate video/MP3; the storyboard and narration below can be handed to a video tool.

Shot 1 · 0–25s
Visual: five puzzle pieces assemble in turn: platform, pipelines, cloud identity, reuse and release, governance.
Narration: in five hours we went from protected branches to components, downstream pipelines, releases, registry governance, and infrastructure state.
Shot 2 · 25–45s
Visual: the readiness checklist is ticked item by item; the score is 25 / 25.
Narration: use the readiness check script to score yourself and find what is not done yet.
Shot 3 · 45–60s
Visual: cleanup arrows: stop environments, destroy resources, delete state, restore settings; the last vault says “components and Releases are kept.”
Narration: stop writes and billing first, then delete dependencies; components and release records are left for the next lesson.
or score ≥ 70% in the quiz

Command cheat sheet

Components · downstream pipelines · Releases · registry governance · deployment strategies · merge trains · managed state
GitLab 19.5 · glab v1.130.0
Components (Module 1)
spec:
  description: "…"
  component: [name, version]
  inputs:
    stage: { default: test }
    versions: { type: array, default: ["3.13"] }
    min: { type: number, default: 80 }
    env: { options: [dev, prod] }
    tag: { regex: ^\d+(\.\d+)*$ }
---
job:
  stage: $[[ inputs.stage ]]
  script: echo $[[ component.version ]]
include:
  - component: $CI_SERVER_FQDN/mygroup-lab/platform/ci-components/python-test@1
    inputs: { coverage_min: 70 }
# self-test: …/$CI_PROJECT_PATH/python-test@$CI_COMMIT_SHA
Publish component / Release (Modules 1, 3)
create-release:
  stage: release
  image: registry.gitlab.com/gitlab-org/cli:latest
  rules: [{ if: $CI_COMMIT_TAG }]
  script: echo "release $CI_COMMIT_TAG"
  release:
    tag_name: $CI_COMMIT_TAG
    description: ./release_notes.md
    assets:
      links:
        - { name: image, url: "https://…", link_type: image }
glab release create v1.0 -N "notes" --milestone v1.0
glab release create v1.2.0 -F notes.md      # updates if it already exists
glab changelog generate --version 1.2.0 --from SHA
glab api "projects/:id/repository/changelog.txt?version=1.2.0&from=SHA"
# In CI: GLAB_ENABLE_CI_AUTOLOGIN=true (do not use GITLAB_TOKEN=$CI_JOB_TOKEN)
Downstream pipelines (Module 2)
child:
  trigger:
    include: ci/e2e.yml          # or [{artifact: g.yml, job: gen}]
    strategy: mirror             # depend: not recommended
multi:
  trigger:
    project: group/other
    branch: main
    strategy: mirror
    inputs: { environment: dev }
    forward: { pipeline_variables: true }
glab api "projects/:id/pipelines/PID/bridges" | jq '.[]|{name,status,d:.downstream_pipeline.status}'
# child: CI_PIPELINE_SOURCE=parent_pipeline; multi-project: pipeline
Registry governance (Module 4)
{ "container_expiration_policy_attributes": {
  "enabled": true, "cadence": "1d", "keep_n": 10, "older_than": "14d",
  "name_regex": ".*", "name_regex_keep": "(?:\\d+\\.\\d+(?:\\.\\d+)?|main)" } }
glab api -X PUT "projects/:id" --input policy.json -H "Content-Type: application/json"
curl --header "JOB-TOKEN: $CI_JOB_TOKEN" --upload-file f.tgz \
  "$CI_API_V4_URL/projects/$CI_PROJECT_ID/packages/generic/NAME/VER/f.tgz"
Deployment strategies (Module 5)
deploy_review:
  environment:
    name: review/$CI_COMMIT_REF_SLUG
    url: $REVIEW_URL            # dotenv
    on_stop: stop_review
    auto_stop_in: 2 days
stop_review:
  variables: { GIT_STRATEGY: none }
  when: manual
  environment: { name: review/$CI_COMMIT_REF_SLUG, action: stop }
rollout 50%:
  when: delayed
  start_in: 5 minutes
  variables: { ROLLOUT_PERCENTAGE: 50 }
glab api -X POST "projects/:id/feature_flags" --input ff.json -H "Content-Type: application/json"
# strategies: default / flexibleRollout / gradualRolloutUserId / userWithId / gitlabUserList
Merging (Module 6)
glab api -X PUT "projects/:id" -f merge_method=rebase_merge -f only_allow_merge_if_pipeline_succeeds=true  # Free
glab api -X PUT "projects/:id" -f merge_pipelines_enabled=true -f merge_trains_enabled=true             # Premium
glab mr rebase 6 && glab mr merge 6
glab api "projects/:id/merge_trains"
rules:
  - if: $CI_MERGE_REQUEST_EVENT_TYPE == "merge_train"   # detached / merged_result / merge_train
Managed state (Module 7)
include:
  - component: $CI_SERVER_FQDN/components/opentofu/validate-plan-apply@5.1.0
    inputs:
      version: 5.1.0
      opentofu_version: 1.13.9
      root_dir: envs/dev
      state_name: dev
      auto_define_backend: true
stages: [validate, build, deploy]
glab opentofu init dev            # -- -migrate-state
glab opentofu state list|lock|unlock|delete dev
Cleanup (Module 8)
glab api -X POST "projects/:id/environments/EID/stop"
glab api -X DELETE "projects/:id/environments/EID"
glab opentofu state delete dev --force
glab api -X DELETE "projects/:id/feature_flags/NAME"
glab repo delete GROUP/PROJECT --yes

Quick troubleshooting table

Symptom / errorMost likely causeFirst step
Component '…@~latest' - content not foundNo published version / wrong path / no permissionglab release list -R component-project
unknown input arguments: xInput name misspelled or removed in a new versionCheck against the Catalog input table
trigger job green, child pipeline redstrategy not setAdd strategy: mirror
downstream pipeline can not be created … emptyall child job rules are unsatisfiedUse parent_pipeline / $CI_MERGE_REQUEST_ID
trigger job stuck on running (depend)downstream waits on a blocking manual jobChange to mirror or run the manual job
glab command not found … v1.58.0release job image lacks glabgitlab-org/cli:latest
glab release 404 in CIGITLAB_TOKEN=$CI_JOB_TOKENChange to GLAB_ENABLE_CI_AUTOLOGIN
changelog requires fromthe previous tag is not vX.Y.ZPass from=SHA
cleanup policy does not delete tagskeep regex / keep_n / older_than / protection rulesWalk through with the evaluator
Review environment not stoppedstop job rules inconsistentsame rules + GIT_STRATEGY: none
Flag always Falseapp_name does not match the environment scopeCheck production / review/*
MR stuck pending (after enabling merged results)no MR pipeline configuredworkflow:rules Add merge_request_event
Error acquiring the state lockLock held / Developer trying to lockglab opentofu state list

Recommended snippet: a “production-grade” skeleton for myapp

include:
  - component: $CI_SERVER_FQDN/mygroup-lab/platform/ci-components/python-test@1
    inputs: { python_versions: ["3.12", "3.13"], coverage_min: 70 }
  - component: $CI_SERVER_FQDN/mygroup-lab/platform/ci-components/docker-build@1
stages: [lint, test, build, verify, deploy, downstream, release]
docker-build:
  tags: [lab-docker]                      # override the component job: build on the self-hosted runner
e2e:            { stage: verify, trigger: { include: ci/e2e.yml, strategy: mirror } }
deploy-config:  { stage: downstream, trigger: { project: mygroup-lab/platform/deploy-config, strategy: mirror } }
release-notes:  { stage: release, … }     # Module 3
release:        { stage: release, … }     # Module 3 (release keyword)

Capstone lab + final quiz

From component to release: python-test@1 → child pipeline (mirror) → v1.3.0 automatic Release → cleanup policy → 25% flag → OpenTofu state
about 45 minCan be completed on Free (merge trains optional)zero cloud cost
Scenario

You are a platform engineer at mygroup-lab. Another team wants to adopt myapp's delivery approach, with these requirements: ① testing and building are provided only through platform components, with controlled versions; ② end-to-end tests run as a child pipeline, and failures must block merging; ③ each vX.Y.Z tag automatically produces a Release with a changelog and asset links; ④ the image registry is cleaned up automatically, but released versions are never deleted; ⑤ new features are rolled out gradually with a flag; ⑥ release metadata (the current version number) is recorded as IaC in GitLab-managed state.

1. Component 1.2.0: give docker-build an input extra_tags (type: array, default []), and in the script run docker tag/push for each extra tag; after the component project's MR self-test passes, tag 1.2.0; confirm that the Catalog shows 1.2.0 and that myapp @1 resolves to 1.2.0 (in the job log component.version).
2. Child pipeline gate: myapp's e2e uses strategy: mirror; in an MR, deliberately make api-e2e fail, confirm the MR cannot be merged because of “pipeline must succeed”; merge after fixing.
3. Semi-linear merge: set the merge method to rebase_merge; open two MRs at the same time and experience “needs rebase” before merging (Premium / trial users switch to merge trains).
4. Publish v1.3.0: make sure at least two merged commits carry the Changelog: trailer; a Maintainer tags v1.3.0; the release-notes job works without passing from (because v1.2.0 is already three-part); the Release includes two asset links (image and generic package), and milestone v1.3 is closed.
5. Registry governance: confirm the cleanup policy next_run_at; the protected container tag rule covers 1.3.0; a Developer pushes :1.3.0 is rejected.
6. Flags: new_counter_ui production 25% (by userId),review/* All users; a local script counts that about 25% of users have it on; then change the percentage to 50% and count again.
7. Record the release in IaC: in platform/infra , change terraform_data.release.input.image_tag to "1.3.0", the MR shows “1 to change”; after merging, apply manually; the state's dev version number goes up by 1.
8. Cleanup: following Module 8, stop the review environments and delete the flag and state (keep the component project and Release).
Acceptance checklist

Open-ended self-test (6 questions)

1. Why is “inputs are safer than variables”? Name two checks that variables cannot do.

Inputs are validated when the configuration is fetched; if validation fails, the pipeline does not start. A misspelled variable just becomes an empty string. Inputs can check: required values, types (number / boolean / array),options allowed values,regex formats, rejecting undeclared keys (unknown input arguments). Array inputs can also replace a whole value with a YAML array (such as a matrix), which variables cannot do.

2. In which two scenarios do the differences between depend and mirror show up? Why should new pipelines choose mirror?

① when the downstream waits on a blocking manual job: depend shows running, while mirror matches the downstream (waiting for manual action); ② a failed downstream job allow_failure: true: depend shows success, while mirror matches the downstream. mirror (18.2+) makes the upstream status match downstream exactly, and the official docs mark depend as not recommended. In addition, only mirror works together with auto_cancel:on_job_failure to cancel the parent pipeline when a child pipeline fails.

3. Why did lesson 2's v1.0 and v1.1 not appear in the changelog calculation? How do you handle history and the future?

By default, tag_regex requires major / minor / patch capture groups (vX.Y.Z), so two-part tags are ignored. History: explicitly pass from for the first three-part version; going forward, always use vX.Y.Z, and the API automatically finds the previous stable version. You can also customize tag_regex, but it must produce a patch capture group.

4. In the cleanup policy, keep_n=10, older_than=14d, and the keep regex is the version number. Will a short-SHA tag from 20 days ago, ranked 5th newest, be deleted?

No. It is within the latest 10, so keep_n excludes it. A tag is deleted only if all of these hold: it matches the delete regex, does not match the keep regex, is not among the latest 10, is older than 14 days, and is not protected or immutable.

5. How can a Free-tier team guarantee that “every commit on main has been tested” without merge trains? What is the cost?

Change the merge method to semi-linear or fast-forward + “pipeline must succeed”: only MRs based on the latest main can be merged, and their MR pipeline tests exactly “main + this MR.” The cost is seriality: each time main moves forward, other ready MRs must rebase and rerun the pipeline.

6. Why is GitLab-managed state “convenient but not suitable for everything”?

Convenient: no extra backend, GitLab permissions, locking and versions, encryption at rest, MR plan reports. Limitations: state is encrypted with the instance key, so it cannot be read when the instance is unavailable, and infrastructure GitLab itself depends on should not be stored only there; plan artifacts are not encrypted and need separate protection; locked writes require Maintainer, and the roles for read-only plans must be kept distinct.

Sources and version notes

All facts were verified on 2026-11-16 against docs.gitlab.com, gitlab.com/gitlab-org, and the component projects; commands not run in real projects have their output labeled “example.”
Verified 2026-11-16

Source

TopicSourceVerified dateFacts used in this lesson
CI/CD components and Catalogdocs.gitlab.com/ci/components2026-11-16Directory structure (only template.yml is published); 100 components per project (18.5); version priority SHA > tag > branch > ~latest/ partial version; pre-releases are not selected; spec:component (18.6 beta, 18.7 GA); self-test uses @$CI_COMMIT_SHA; publishing prerequisites (Owner enables Catalog, description, README, templates,release keyword, semantic-version tag); visibility; 17.0 GA; analytics 18.9, usage details 19.0 (Premium); troubleshooting content not found,Spec must be a valid json schema; security practices
CI/CD inputsdocs.gitlab.com/ci/inputs2026-11-16types string / number / boolean / array, default / options / regex / description / rules (18.7); evaluation timing; 1 KB / 1 MB limits; at most 3 functions; quoting issues in rules; at most 20 inputs per pipeline
Downstream pipelinesDownstream pipelines · trigger · Troubleshooting2026-11-16parent-child / multi-project differences; two-level nesting; limit of 1000; at most 3 configuration files; dynamic child pipeline and variable limits; CI_PIPELINE_SOURCE; strategy: mirror introduced in 18.2,depend not recommended and its two differences; keywords usable in trigger; trigger:inputs 17.11; forward default value; needs:project pulling artifacts is Premium; errors “resulting pipeline would have been empty” and “Ref is ambiguous”
Releases and release-clirelease keyword · Releases · Release CLI (deprecated) · glab release create2026-11-16release keyword uses glab, image gitlab-org/cli:latest, CI_JOB_TOKEN and token priority, fails if it already exists; release-cli deprecated in 18.0, planned removal in 20.0; ci_glab_for_release introduced in 18.0, GA in 18.4; glab ≥ 1.58.0; GLAB_ENABLE_CI_AUTOLOGIN; do not GITLAB_TOKEN=$CI_JOB_TOKEN; permanent links; deployment freezes; glab options (--assets-links,--no-update,--use-package-registry, experimental --publish-to-catalog)
ChangelogChangelogs · Repositories API2026-11-16trailer categories; glab changelog generate (glab 1.30+); API GET / POST, CI_JOB_TOKEN (17.7),.txt (19.1),config_file_ref (18.2), v-prefix equivalence (17.0); the default tag_regex requires major / minor / patch; without from, it automatically finds the previous X.Y.Z/vX.Y.Z tag
Container / package registriescleanup policy · protected container tags · immutable container tags · package storage2026-11-1610-step evaluation order and official example; API legal values; RE2 and automatic anchoring; GitLab.com single-run time limit; layers deduplicated within the root namespace, untagged layers after 24 hours; protected tags Free 17.11 GA, 5 rules; immutable tags Ultimate 18.10 GA; package cleanup policy about every 12 hours, duplicate asset definition
Deployment strategiesReview apps · Incremental rollouts · Feature flags · Feature flags API2026-11-16Review App dynamic environment example; progressive rollout ROLLOUT_PERCENTAGE, manual / scheduled (default 5 min); flags Free, .com limits 50 / 150 / 200; strategy names; API URL / Instance ID / Application name; “search code references” Premium; minimum role setting 19.4 (feature flag)
Merge trains / merged resultsMerge trains · Merged results pipelines · Projects API2026-11-16Premium / Ultimate; workflow and failure re-ordering example; auto-merge joins the train (17.7 GA); cost of merge immediately; experimental skip-train feature; concurrency limit 20 (adjustable in 19.0); prerequisites; merge_pipelines_enabled,merge_trains_enabled,merge_method (merge / rebase_merge / ff)
IaC and managed stateIaC with OpenTofu · GitLab-managed state · Deprecations · components/opentofu2026-11-16OpenTofu component is the recommended way; Terraform templates deprecated in 16.9, removed in 18.0; component 5.1.0 (2026-11-06), optional OpenTofu 1.13.9 / 1.13.2 / 1.12.12 / 1.12.11; inputs version,state_name,root_dir,auto_define_backend,allow_developer_role_to_plan,plan_artifacts_access (default none),trigger_in_child_pipeline,enable_id_tokens,id_tokens_setup_script; compatible with N-2 GitLab versions; Lockbox encryption and disaster-recovery notes; plan not encrypted; role requirements; glab opentofu (18.3 / glab 1.66); manual init parameters
Versionsdocs.gitlab.com/releases · glab releases2026-11-16GitLab 19.5 (patch 19.5.6) is the latest released version; glab v1.130.0; Runner v19.5.3 (carried over from lessons 1–4)
Companion coursesTerraform course · GitHub course · Azure DevOps course · Jenkins course—Terraform itself and reuse / orchestration approaches on other platforms

Video verification notes

All listed videos were verified on 2026-11-16 by title and channel via YouTube oEmbed (https://www.youtube.com/oembed?url=…&format=json):

No verified dedicated videos were found for: Releases + changelog API (new glab path), container registry cleanup policies / protected container tags,strategy: mirror— storyboard scripts are provided for them. Most official videos were recorded earlier (before mirror, the OpenTofu component, and the glab release path); where they conflict with this lesson, this lesson and the official docs take precedence.

Audio notes

The “Audio” tab uses the browser's built-in Web Speech API: the Chinese narration uses the zh-CN voice, and English terms use the en-US voice. This courseware cannot embed MP3; without a Chinese voice pack, the narration scripts can still be read directly or handed to another TTS tool.

Known limitations

  • When this courseware was written,these commands and pipelines were not run in a real GitLab.com project; all outputs are “examples” constructed from the official docs; project IDs, pipeline IDs, commit SHAs, dates, and URL suffixes are placeholder values.
  • Error wording for input validation: unknown input arguments verified in the GitLab source code; the remaining wording, such as “provided value is not a number” and “not in the list of allowed options,” follows GitLab's “<input name> input: …” format,subject to the actual pipeline errors. Verbatim error text for a missing from in the changelog, invalid cleanup policy values, environment deletion, and so on is also subject to the actual response.
  • strategy: mirror For the “downstream failed job with allow_failure” scenario: the docs only say “exactly matches downstream”; the animation displays it this way (success; any warning is up to the UI).
  • Whether runtime variables can be expanded in trigger inputs is not clearly documented; this lesson therefore passes runtime values via trigger variables,trigger:inputs and only passes static values.
  • The Azure cloud deployment for Review Apps, the Container Apps approach for progressive rollout, and the OpenTofu Azure OIDC fragment are optional: they need lesson 3's resources (most already cleaned up in lesson 3) and an extra review identity / flexible federated credential. The commands were adapted from the Azure CLI and azurerm provider docs and were not actually run; az containerapp revision list JMESPath queries should be adjusted to the actual revision naming.
  • The Python UnleashClient constructor parameters (disable_metrics,disable_registration) follow the docs of the installed version; GitLab docs only provide examples in Go, Ruby, and others.
  • Merge trains and merged results pipelines require Premium / Ultimate; the return behavior of calling merge_trains_enabled and similar parameters on Free follows the actual response. GitLab.com trial terms follow about.gitlab.com.
  • glab The subcommand output format changes between versions (for example glab opentofu state list,glab ci get fields); the examples are for reference only. alpine:3.22,hashicorp/random ~> 3.7 are example versions.
  • The master branch of the official docs already contains 19.6 entries (such as Maven snapshots for package cleanup policies and not-downloaded cleanup for generic packages); 19.6 is not yet released and is not used in this lesson.