GitLab Hour 5: Production-Grade CI/CD — Reuse, Releases, and Orchestration
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- Write a component project (
templates/,spec:inputstype/default/options,spec:componentcontext), use@$CI_COMMIT_SHAto self-test, usereleasekeyword 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 predictstrategy(withoutdepend/mirror) how downstream status propagates upstream. - Retroactively create a Release for the lesson 2
v1.0tag, use Git trailers and the changelog API to auto-generate release notes, and in tag pipelines use thereleasekeyword (now implemented withglab) to publishv1.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
| # | Time | Module | Core content | Animation / interactive | Lab |
|---|---|---|---|---|---|
| 0 | Before class | Prep: multi-project sample group | In mygroup-lab/platform create ci-components,deploy-config, and infra three projects; record their project IDs | Prerequisite self-check | glab repo create,glab api |
| 1 | 00–06 | CI/CD components and CI/CD Catalog | component directory structure,spec:inputs types and validation,spec:component, self-test, semantic-version release, Catalog visibility | component input parser (including 6 failure scenarios) | Publish python-test@1.0.0 and use it in myapp |
| 2 | 06–13 | Parent-child and multi-project pipelines | trigger:include / project / forward / inputs, dynamic child pipelines,strategy: depend vs mirror, nesting, and permission restrictions | Core animation: upstream and downstream status propagation | parent-child + dynamic child pipeline + trigger deploy-config |
| 3 | 13–21 | Releases, tags, and changelogs | Release object,release keyword (glab),glab release create, Changelog trailers and API, asset links, permanent links, deployment freezes | Tag → release pipeline, step-by-step replay | Backfill a Release for v1.0; publish v1.2.0 |
| 4 | 21–28 | Packages and container registry | CI_REGISTRY_IMAGE, evaluation order of cleanup policies, protected and immutable container tags, generic and PyPI packages, package cleanup policies | cleanup policy evaluator | Configure a cleanup policy + publish a generic package |
| 5 | 28–35 | Deployment strategies: progressive rollout, Feature Flags, and Review Apps | dynamic environments,on_stop,auto_stop_in; manual or scheduled progressive rollout; Unleash-compatible Feature Flags and strategies | traffic percentage × flag percentage simulator | MR Review App lifecycle + 25% Feature Flag |
| 6 | 35–42 | Merge trains and merged results pipelines | merged results commits, train queuing and restart, concurrency limit of 20; Free alternative: semi-linear or fast-forward merges | merge train simulator (re-ordering after B fails) | Free: semi-linear merge walkthrough; Premium: enable trains |
| 7 | 42–50 | Infrastructure as code: GitLab-managed Terraform state | OpenTofu component 5.1.0, HTTP backend and locking,glab opentofu, the plan report in MRs, plan file security | State locking and versioning (two pipelines competing) | Zero-cost tofu project: plan → apply → lock conflict → version history review |
| 8 | 50–60 | Recap of the first five hours, self-test, and cleanup | Knowledge map for the five lessons, readiness check, cleanup in dependency order, interactive troubleshooting tree | Knowledge map + troubleshooting tree | Cleanup script |
| — | After class | Cheat sheet · Capstone lab | Components → parent-child orchestration → v1.2.0 release → cleanup policies → Feature Flag → IaC state | Final quiz (12 questions) | Capstone lab |
Knowledge Coverage Matrix
| Target skills | M1 | M2 | M3 | M4 | M5 | M6 | M7 | M8 | Key commands / keywords | Lab |
|---|---|---|---|---|---|---|---|---|---|---|
| Write, test, and release a CI/CD component | ✓ | ✓ | ✓ | · | · | · | ✓ | ✓ | spec:inputs,include:component,release | M1 |
| Parent-child / multi-project / dynamic child pipeline orchestration | · | ✓ | · | · | ✓ | · | ✓ | ✓ | trigger,strategy: mirror,include:artifact | M2 |
| Predict upstream and downstream status propagation | · | ✓ | · | · | · | ✓ | · | ✓ | strategy: depend / mirror | M2 animation |
| Releases, changelogs, assets | ✓ | · | ✓ | ✓ | · | · | · | ✓ | glab release create,/repository/changelog | M3 |
| Container and package registry and storage governance | · | · | ✓ | ✓ | · | · | · | ✓ | container_expiration_policy_attributes,packages/generic | M4 |
| Review Apps and dynamic environments | · | · | · | · | ✓ | ✓ | · | ✓ | environment:on_stop,auto_stop_in | M5 |
| Progressive rollout and Feature Flags | · | · | · | · | ✓ | · | · | · | when: delayed,/feature_flags, Unleash | M5 |
| Merged results pipeline / merge trains / Free alternative | · | · | · | · | · | ✓ | · | ✓ | merge_trains_enabled,merge_method | M6 |
| GitLab-managed OpenTofu state | ✓ | ✓ | · | · | · | · | ✓ | ✓ | backend "http",glab opentofu | M7 |
What this lesson does not cover (and where to learn it)
| Topic | Why it is not in this lesson | Where to learn |
|---|---|---|
HCL syntax, providers, module design,terraform test, state internals | This lesson only covers how GitLab stores state and how to run IaC in pipelines | Terraform 8-hour course |
include merge rules,rules,needs Basics and referencing official components | Covered 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 there | Lesson 3 · Lesson 4 |
| Security scanning, SBOM, signing, pipeline execution policies | Belongs to the “DevSecOps and supply chain” topic | Lesson 6 |
| Canary on Kubernetes (Ingress weights, Argo Rollouts) | Belongs to Kubernetes platform capabilities; this lesson only covers GitLab-side orchestration | Kubernetes course |
| How the same topic is written in GitHub Actions / Azure Pipelines / Jenkins | This lesson covers GitLab only | GitHub · Azure DevOps · Jenkins |
How to use this courseware
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.
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).
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.
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.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)
mygroup-lab/platform create three new projects as the “platform team” component library, deployment configuration repository, and infrastructure repository- Completelesson 2:
mygroup-lab/myapp's.gitlab-ci.yml(stageslint / test / build / verify,python-lint,unit-testmatrix,integration-test,build-image,smoke) merged, the tagv1.0published, imageregistry.gitlab.com/mygroup-lab/myapp:1.0exists. - Cloud resources from lessons 3 and 4 may already be cleaned up; this lesson does not depend on them. Lesson 3's
v1.1tag, if it exists, will be treated as the previous version in this lesson's release notes. - In
mygroup-labyou are Owner (publishing to the Catalog requires the Owner role on the component project),glab auth statusthat is normal; this machine hasgit,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 platform | All 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"
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).
Module 1 · CI/CD components and CI/CD Catalog
- Write a compliant component project:
templates/<name>.ymlortemplates/<name>/template.yml, a root directoryREADME.md, and do not use global keywords. - Be proficient with
spec:inputsof thetype(string / number / boolean / array),default,options,regex,description, andspec: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_SHAto self-test the component, usereleasekeyword to publish semantic versions, so the project appears in the CI/CD Catalog.
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 structure | Root 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 |
| Limit | Each project allows at most 100 components (from 18.5, previously 30); components that need an independent release cadence should go in separate projects |
| Same instance | can 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) |
| Access | Private component projects: consumers need the Reporter role or higher on the component project (inherited from group membership is sufficient) |
spec Available keywords | description,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
optionsthe list, values that do not matchregex, 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
@1existing 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
| Syntax | Meaning | Suitable for |
|---|---|---|
@e3262fdd… (full SHA) | Highest priority; SHA takes precedence over a tag with the same name | Production pipelines with the highest security requirements (recommended by official docs) |
@1.0.0 (tag) | Catalog publishing must use semantic versions | General production use |
@main (branch) | Tags take precedence over branches with the same name | Only for testing |
@1 / @1.2 / @~latest | Latest matching version published in the Catalog; pre-release versions are never selected (e.g., 1.0.1-rc); only applies to Catalog projects | When 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:localis enough. - When a whole sub-process (such as OpenTofu's validate/plan/apply) needs to be handed to consumers → component + (optional)
trigger:include:componentas a child pipeline (Modules 2, 7).
Comparison with similar technologies
| GitLab components | GitHub reusable workflows / Actions | Azure Pipelines templates | Jenkins shared libraries | |
|---|---|---|---|---|
| Interface | spec:inputs (types, options, regex) | inputs (types, required) | parameters (types, values) | Groovy function parameters |
| Version | SHA / tag / branch / partial semver | SHA / tag / branch | resources.repositories ref | @Library('x@1.0') |
| Discovery | CI/CD Catalog | Marketplace | No unified directory | No unified directory |
| See | this lesson | GitHub course | Azure DevOps course | Jenkins course |
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
Input parsing flow (when a pipeline is created)
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).
Common commands and keywords
| Command / keyword | Purpose | Key parameters / notes |
|---|---|---|
include: - component: $CI_SERVER_FQDN/<path>/<name>@<version> | Reference a component | inputs: pass inputs; rules can be included conditionally |
spec: inputs: x: {type, default, options, regex, description} | Declare the interface | None default i.e., required; type defaults to string |
spec: component: [name, version, sha, reference] | Declare the component context needed | Use $[[ component.version ]] to reference (18.7 GA) |
glab ci lint | Local validation .gitlab-ci.yml | includes component parsing and input validation |
glab api graphql -f query='mutation{catalogResourcesCreate(…)}' | Turn a project into a Catalog project | Equivalent to the UI toggle; requires Owner; this GraphQL change is marked Experiment |
glab release list -R <component project> | List published versions | Corresponds to the Catalog's version list |
glab ci config compile | View the full merged configuration | Verify 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:inputsis empty, causing the release to reportSpec must be a valid json schema(if no inputs are needed, write an emptyspec:). - 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)
~/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.tomlcat > 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.
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).
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).
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.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.
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: falseThe 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
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.
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.
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.
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.
Module 2 · Parent-child pipelines and multi-project pipelines
- 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:includeinclude (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: mirroris 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.
rules / needs / artifacts. Importance:★★★★★What: two kinds of downstream pipelines
| parent-child pipeline | multi-project pipeline | |
|---|---|---|
| Syntax | trigger: include: … | trigger: project: mygroup-lab/platform/deploy-config (can add branch) |
| Run in | the same project, same ref, same commit SHA | downstream project; by default, the default branch of the downstream project; branch can specify a branch or tag |
$CI_PIPELINE_SOURCE | parent_pipeline | pipeline |
| Pipeline list | does not appear in the project's pipeline list; only visible in the parent pipeline's details | appears in the downstream project's pipeline list |
| Effect on ref status | Only when strategy is set does it affect that ref's status | affects the downstream project's ref status; if strategy is not set, it does not affect the upstream ref |
interruptible Auto-cancel | when a new pipeline on the same ref starts, it is canceled along with the parent pipeline | is not canceled by new upstream pipelines (it can be canceled when the downstream project has its own new pipeline) |
| Nesting | up to two levels child pipelines (parent → child → grandchild) | are independent of each other, with no nesting limit |
| Permissions | same as the parent pipeline | Triggering 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)
| Case | No strategy | strategy: depend (official: not recommended) | strategy: mirror (18.2+, recommended) |
|---|---|---|---|
| When the trigger job ends | Downstream is created successfully→ passed | waits for downstream to finish | waits for downstream to finish |
| When later stages start | Immediately (in parallel) | After downstream succeeds | After downstream succeeds |
| A downstream job fails | trigger remains passed; upstream may be all green | failed | failed |
A failed downstream job with allow_failure: true | passed | shows success (downstream is treated as successful) | same as downstream status |
| Downstream has a blocking manual job waiting | passed | shows running (waits indefinitely) | same as downstream (waiting for manual action) |
| downstream has an optional manual job | does 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 |
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
variablesand the trigger job's ownvariablesdefaults are passed down as trigger variables (trigger:forward:yaml_variables: true). - Pipeline variables (entered manually when running, from scheduled jobs,
needsjob dotenv variables) by default are not passed; you need totrigger:forward:pipeline_variables: true; forwarded variables are not automatically forwarded to grandchild pipelines. - Runner
config.tomlenvironment variables and predefined “job-only” variables are not available in trigger jobs. - Available since 17.11:
trigger:include:inputs(child) andtrigger:inputs(multi-project) to the downstream configuration'sspec:inputsvalues — safer than variables, because they have types and validation. - In child pipelines,
$CI_PIPELINE_SOURCEis alwaysparent_pipeline: to make child jobs run only when the parent pipeline is an MR pipeline, useif: $CI_MERGE_REQUEST_ID(the parent pipeline'sCI_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
needsand stages are enough; downstream pipelines add troubleshooting and permission complexity.
Comparison with similar technologies
| GitLab | GitHub Actions | Azure Pipelines | Jenkins | |
|---|---|---|---|---|
| Trigger another pipeline | trigger:include / trigger:project | Reusable workflows uses: / workflow_dispatch + API | Templates / resources.pipelines trigger | build job: 'x', wait: true |
| waits and inherits status | strategy: mirror | reusable workflows are naturally synchronous | pipeline resource triggers are asynchronous | wait: true, propagate: true |
$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
Status propagation of strategy
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.
Keywords and commands at a glance
| Syntax | Purpose | Notes |
|---|---|---|
trigger: include: ci/e2e.yml | Static child pipeline | combine up to 3 configuration files |
trigger: include: [{artifact: generated.yml, job: generate-config}] | Dynamic child pipeline | path 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 configuration | access rules same as include:component |
trigger: project: path + branch: branch name | Multi-project pipeline | project / branch supports variable expansion (excluding job-only variables) |
trigger: strategy: mirror | waits for and mirrors downstream status | 18.2+; depend still available but not recommended |
trigger: forward: {yaml_variables, pipeline_variables} | control which variables are forwarded | default true / false |
glab ci view / glab ci get -b main | View pipeline (including downstream bridge jobs) | glab ci get output JSON |
glab api projects/:id/pipelines/:pid/bridges | list trigger (bridge) jobs and their downstream pipelines | Field 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)
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
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.
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.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)
deploy-config The job fails, with a message that it lacks permission to create the downstream pipeline.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+).
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).
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
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.
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.
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.
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.
Module 3 · Releases, tags, and changelogs
- Explain the relationship among Git tags, protected tags, Releases, milestones, and Release evidence; backfill a Release for the existing lesson 2
v1.0tag. - You will create Releases in CI in two ways:
releasekeyword (since GitLab 18.0 it is implemented by callingglab release create) and directly in a script withglab release create, and know the authentication method of each. - Use
Changelog:Git trailers + the changelog API /glab changelog generateto 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.
v1.0 tag pipeline. Importance:★★★★What: tags and Releases
| object | belongs to | content | Who can create (set in this lesson) |
|---|---|---|---|
| Git tags (lightweight / annotated) | Git | point to a commit; annotated tags also carry an author and a message | protected tags *: Maintainer only |
| Release | GitLab | name, release notes (Markdown), asset links, source archives, milestones, Release evidence, release date | Developers and above can create Releases; but to create a Release for a protected tag requires permission to create that tag |
| milestone | GitLab | a 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 evidence | GitLab | JSON snapshot generated automatically at creation time (milestones, issues, etc.) | automatic |
How: two ways to create a Release in CI
release keyword | in a script glab release create | |
|---|---|---|
| image | job $PATH must have glab: Docker executor uses registry.gitlab.com/gitlab-org/cli:latest | same as left |
| authentication | default CI_JOB_TOKEN; if the job defines GITLAB_TOKEN / GITLAB_ACCESS_TOKEN / OAUTH_TOKEN then those take precedence | set 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 timing | script After after_script before; created only if the script succeeds | anywhere in the script |
| An existing Release | is not updated; the job fails | by default updates an existing Release (--no-update prevents this) |
| publish to the CI/CD Catalog | must use it (Module 1) | Not possible (--publish-to-catalog is still an experimental feature and requires a feature flag) |
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.7CI_JOB_TOKEN, supported since 19.1.txtplain text) andPOST …/changelog(generates and commits toCHANGELOG.md); CLI:glab changelog generate. versionMust be a semantic version (since 17.01.2.0andv1.2.0are equivalent). Withoutfrom, GitLab automatically finds the “previous stable version tag,” and only recognizesX.Y.Z/vX.Y.Z.- Configuration file
.gitlab/changelog_config.yml:categories(title mapping),template,date_format,tag_regex(must producemajor/minor/patchcapture group, otherwise the tag is ignored),include_groups; parsing time limit 2 seconds.
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
| GitLab | GitHub | Azure DevOps | |
|---|---|---|---|
| Release object | Release (tag-based) + evidence + milestones | Release (tag-based) + auto-generated notes | no object with the same name (Classic Release is a deployment pipeline) |
| creating in CI | release release keyword / glab release create | gh release create | GitHub Release task or REST |
| changelog | commit trailer + API | auto notes based on PR labels | needs a third party |
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
How the changelog API determines the commit range
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.
Commands at a glance
| Command | Purpose | Key parameters |
|---|---|---|
glab release create v1.0 -N "…" | Create a Release for an existing tag | If 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-registry | upload a file to the generic package registry and link it | --package-name default release-assets |
glab release list / view / download / delete | manage Releases | -R specify project |
glab changelog generate --version 1.2.0 --from SHA | preview the changelog locally | glab ≥ 1.30; default trailer Changelog |
GET /projects/:id/repository/changelog.txt?version=1.2.0 | generate plain-text log (19.1+) | use in CI JOB-TOKEN header (17.7+) |
POST /projects/:id/repository/changelog | generate and commit to CHANGELOG.md | branch,file,message |
glab api projects/:id/freeze_periods | manage deployment freezes | cron 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.0is released, the nextv1.3.0will 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 throughneeds.- Deployment freeze:
$CI_DEPLOY_FREEZEonly exists within the freeze window,== nullso the release job does not appear during the freeze period. - Version prefix:
release:nameVariables 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)
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).
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
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`
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).
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.
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)
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:
Official docs
- Releases
- GitLab Release CLI tool (deprecated)
- Changelogs
- Repositories API: changelog
- glab release create
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.
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.
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.
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.
Module 4 · Packages and the container registry
- Use predefined variables
CI_REGISTRY,CI_REGISTRY_IMAGE,CI_REGISTRY_USER,CI_REGISTRY_PASSWORDto 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 → keepkeep_n→ exclude those newer thanolder_than→ exclude protected / immutable tags → delete. - Configure cleanup policies with the API (
cadence,keep_n,older_thanlegal values), and use protected container tags to protect release versions. - Publish generic and PyPI packages, and configure package cleanup policies (duplicate asset retention count).
What: two registries
| container registry | package registry | |
|---|---|---|
| Address | registry.gitlab.com/mygroup-lab/myapp[/subpath]:tag ($CI_REGISTRY_IMAGE) | $CI_API_V4_URL/projects/:id/packages/<format>/… |
| Format | OCI / 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 authentication | docker 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 calculation | layers 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 online | Every asset file counts; re-uploading the same name and version stacks assets |
| Automatic governance | cleanup policies (by tag) | cleanup policies (duplicate asset retention count; runs about every 12 hours) |
How: the evaluation order of cleanup policies (official 10 steps)
- collect all tags in the repository;
- exclude
latest(always kept); - use
name_regex(the ones to delete) to filter; non-matching ones are excluded; - matching
name_regex_keep(the ones to keep) exclusion; - exclude tags with no manifest;
- sort by creation time;
- exclude the latest
keep_n(per image name); - exclude those newer than
older_than; - exclude protected tags and immutable tags;
- 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 |
|---|---|
cadence | 1d,7d,14d,1month,3month |
keep_n | 1,5,10,25,50,100 |
older_than | 1d,3d,7d,14d,30d,60d,90d,180d,365d,730d,1095d |
name_regex / name_regex_keep | RE2 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 tags | Immutable container tags | |
|---|---|---|
| Tier | Free (17.11 GA) | Ultimate (18.10 GA) |
| Purpose | restrict who can push / delete matching tags (minimum role Maintainer / Owner / Administrator) | matching tags after creation anyone cannot overwrite or delete |
| Quantity | at most 5 rules per project, regex ≤ 100 characters | per official docs |
| and | are 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
| GitLab | GitHub Packages / GHCR | Azure Artifacts / ACR | |
|---|---|---|---|
| Automatic cleanup | project-level cleanup policies (UI / API) | need an Action or API to delete versions | ACR retention policies / tasks; artifact retention policies |
| Tag protection | protected (Free) / immutable (Ultimate) | no equivalent feature | ACR lock (write-enabled=false) |
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
Asset stacking in the package registry
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.
Commands at a glance
| Command | Purpose | Notes |
|---|---|---|
glab api -X PUT projects/:id --input policy.json | Set cleanup policy | in the JSON container_expiration_policy_attributes |
glab api projects/:id | jq .container_expiration_policy | View policy and next_run_at | |
glab api "projects/:id/registry/repositories?tags=true&tags_count=true" | List container repositories and tags | read-only |
glab api -X DELETE "projects/:id/registry/repositories/:rid/tags/:tag" | Delete a single tag | protected 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 package | version 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 package | the 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.
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)
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
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
glab 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.
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=30d2. 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"
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:
Official docs
- Reduce container registry storage (cleanup policies)
- Protected container tags
- Immutable container tags
- Reduce package registry storage
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.
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.
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.
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.
Module 5 · Deployment strategies: progressive rollout, Feature Flags, and Review Apps
- Create a Review App for each MR: dynamic environment name
review/$CI_COMMIT_REF_SLUG,environment:url,on_stop, stop jobauto_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).
What: three ways to reduce release risk
| Review Apps | Incremental rollouts | Feature Flags | |
|---|---|---|---|
| Controls | one temporary environment per branch / MR | what proportion of instances / traffic runs the new version | which users have a feature turned on |
| GitLab mechanism | dynamic environments + on_stop + auto_stop_in | a 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 method | closing the MR stops it | run 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 |
| Tier | Free | Free (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_SLUGAt most 24 characters, only lowercase letters, digits, and hyphens; suitable for composing resource names. - Stop job: same environment name +
action: stop, usuallywhen: manual;GIT_STRATEGY: noneso it can still run after the branch is deleted. - When the stop is triggered: manually clicking “Stop,”
auto_stop_inexpiry, 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
- In Deploy → Feature flags, create a flag (or via API
POST /projects/:id/feature_flags,version: new_version_flag). - 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). - 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 asproduction), which is used to match the environment scope. - 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
| GitLab | GitHub | Azure | |
|---|---|---|---|
| temporary environments | Review Apps (dynamic environments) | deployment environments + self-built workflows | Container Apps revisions / deployment slots |
| flag service | built-in Unleash-compatible Feature Flags | no built-in (third party) | Azure App Configuration Feature Manager |
Risk control chain from MR to production
Feature Flag evaluation (in the app)
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.
Keywords and commands
| Syntax / command | Purpose | Notes |
|---|---|---|
environment: {name: review/$CI_COMMIT_REF_SLUG, url, on_stop, auto_stop_in} | dynamic environment | The / in the environment name makes the UI group them in one folder. |
environment: {name: …, action: stop} + GIT_STRATEGY: none | stop job | can still run after the branch is deleted |
when: delayed + start_in: 5 minutes | scheduled job | during the countdown, you can run it immediately or cancel it |
glab api projects/:id/environments?states=available | list environments | POST …/environments/:id/stop stop |
glab api -X POST projects/:id/feature_flags --input ff.json | create flag | PUT …/feature_flags/:name modify |
glab api -X POST projects/:id/feature_flags_user_lists | create user list | user_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
…: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)
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).
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.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.
glab api -X DELETE "projects/:id/feature_flags/new_counter_ui", or keep it for the unified cleanup in Module 8.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.
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"}}]}')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
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.
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.
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.
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.
Module 6 · Merge trains and merged results pipelines
- 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.
workflow:rules. Importance:★★★★What: three kinds of MR pipelines
| Type | Code tested | CI_MERGE_REQUEST_EVENT_TYPE | Tier |
|---|---|---|---|
| MR pipeline (detached) | source branch HEAD | detached | Free |
| merged results pipeline | A temporary merge commit of the source and target branches (not on any branch); on conflict, it falls back to a regular MR pipeline | merged_result | Premium / Ultimate |
| merge train pipeline | target branch + all MRs ahead of it in the train + this MR | merge_train | Premium / 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)
- 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.
- When later MRs join, each pipeline tests “target + all MRs ahead + itself,” and the pipelines run in parallel.
- An MR is merged only after its own pipeline succeeds and all MRs ahead of it have been merged.
- 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.
- “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).
- 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
| Option | How | Guarantee | Cost |
|---|---|---|---|
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 commits | Combined with “pipeline must succeed,” the combination being merged is exactly the one the MR pipeline tested | Each 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 linear | Same as above | Same as above; the merge commit habit from lesson 1 has to change |
| Do the “merged result” yourself inside the MR pipeline | In the job, git fetch origin main && git merge --no-edit origin/main before testing. | approximate merged results pipeline | still cannot sense other MRs being merged concurrently; not fully identical to a real merge commit |
| main pipeline + fast rollback | when main fails, automatically open a revert MR and notify | discovered afterwards | main may be briefly broken |
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
| GitLab | GitHub | Azure Repos | |
|---|---|---|---|
| merge queue | Merge trains (Premium) | Merge queue (per GitHub docs) | no built-in (use branch policies + build verification) |
| test merged result | merged results pipeline (Premium) | pull_request events are based on the merge commit by default | PR builds are based on the merge commit by default |
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
Free: the serial pace of semi-linear merges
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.
Settings and commands
| Command / setting | Purpose | Tier |
|---|---|---|
glab api -X PUT projects/:id -f merge_pipelines_enabled=true | Enable merged results pipelines | Premium |
glab api -X PUT projects/:id -f merge_trains_enabled=true | Enable merge trains | Premium |
glab api -X PUT projects/:id -f merge_method=rebase_merge | Semi-linear merge (ff is fast-forward,merge is a regular merge commit) | Free |
glab mr merge 6 | When the train is enabled: join the train (if the pipeline is running, set auto-merge,--auto-merge default true) | — |
glab mr rebase 6 | server-side rebase of the source branch (commonly used with semi-linear / fast-forward) | Free |
glab api projects/:id/merge_trains | view MRs in the train and their status | Premium |
glab api -X PUT projects/:id/merge_requests/:iid/merge -f skip_merge_train=true | skip 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)
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.
glab mr create one revert MR).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.
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.
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"
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
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.
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.
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.
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.
Module 7 · Infrastructure as code: GitLab-managed Terraform state
- Explain how GitLab-managed state works: the OpenTofu / Terraform
httpbackend →/api/v4/projects/:id/terraform/state/:name(GET / POST for read and write;/lockPOST / 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.0to build a fmt → validate → plan → manual apply pipeline, and understandstate_name,root_dir,auto_define_backend,trigger_in_child_pipeline,enable_id_tokensand similar inputs. - Use
glab opentofu init / state list / lock / unlock / deleteto access the state locally, and know the role requirements (a Developer can onlyplan -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).
What: four things GitLab provides for IaC
| Capability | Description | Tier |
|---|---|---|
| GitLab-managed state | each 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 integration | The 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 registry | Terraform / OpenTofu module registry (a format of the package registry) | Free |
| OpenTofu CI/CD component | gitlab.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 script | Free |
How: what the HTTP backend does during an apply
gitlab-tofu initautomatically configured from CI variableshttpbackend: address$CI_API_V4_URL/projects/$CI_PROJECT_ID/terraform/state/$GITLAB_TOFU_STATE_NAME, lock address…/lock, authentication uses the job token (usernamegitlab-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).plan:POST …/lockacquire lock →GETread latest state → refresh and compute the diff → write outplan.cacheandplan.json(artifacts) →DELETE …/lockrelease the lock.apply(manual job): re-lock, run the same plan file,POSTand write the new state (serial + 1; GitLab saves it as a new version), then release the lock.- 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).
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
| Operation | Minimum 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 state | S3 backend (use_lockfile) | azurerm backend | HCP Terraform | |
|---|---|---|---|---|
| lock | HTTP /lock | S3 native lock file | Blob lease | workspace lock |
| authentication | GitLab token / job token | AWS credentials | Azure credentials | HCP token |
| version history | built-in | S3 versioning | Blob versions / snapshots | built-in |
| See | this lesson | Terraform 8-hour course(backends, state internals, team collaboration) | ||
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
Multiple environments: one child pipeline per state
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.
Commands at a glance
| Command | Purpose | Notes |
|---|---|---|
glab opentofu init dev | Initialize the current directory against the GitLab state locally dev | glab ≥ 1.66 (GitLab 18.3+); -d directory,-b terraform uses the Terraform binary; -- -migrate-state passthrough arguments |
glab opentofu state list | list the project's states | -F json |
glab opentofu state lock|unlock dev | manually lock / unlock | confirm 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 / apply | wrapper script in the component image | GITLAB_TOFU_STATE_NAME,GITLAB_TOFU_ROOT_DIR and similar variables |
tofu init -backend-config=address=… -backend-config=lock_address=…/lock … | Manual init without glab | lock_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)
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.
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.
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.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.
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.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.
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 }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
Official docs
- Infrastructure as Code with OpenTofu and GitLab
- GitLab-managed Terraform/OpenTofu state
- OpenTofu CI/CD component (README)
- glab opentofu
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.
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.
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.
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.
Module 8 · Recap of the first five hours, self-test, and cleanup
- 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.
Five-hour knowledge map
| Lesson | Topic | Core objects / keywords | Role in lesson 5 |
|---|---|---|---|
| Lesson 1 | Platform basics | groups mygroup-lab / sub-groups platform, roles, protected branches and tags, MRs, approvals, merge methods | component projects inherit members; protected tags decide who can publish components and Releases; merge methods are the Free alternative in Module 6 |
| Lesson 2 | CI/CD basics | .gitlab-ci.yml,workflow:rules,needs, include, Runner,v1.0 | jobs replaced by components; MR pipelines are the prerequisite for merge trains; v1.0 backfill Release |
| Lesson 3 | Azure | id_tokens, federated credentials, Container Apps revision weights, environments | progressive rollout, Review Apps, and the optional Azure fragment for OpenTofu |
| Lesson 4 | AWS | STS, ECR immutable tags, ECS circuit breaker, multi-account | “deploy by digest / version” complements Module 4's cleanup policies |
| Lesson 5 | Production-grade CI/CD | components / Catalog, trigger / strategy, Release / changelog, registry governance, Review Apps / progressive rollout / Feature Flags, merge trains, managed state | —— |
The eight key conclusions of this lesson
- Component =
spec:inputsinterface + semantic version + Catalog; inputs are validated when the configuration is fetched, earlier and stricter than variables. - Catalog versions can only be created by the CI
releasekeyword;@1,~latestonly match published versions. - trigger jobs do not use a runner; without
strategy, downstream failures do not flow back; for new pipelines usemirror(18.2+),dependhas two inconsistent scenarios. - 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. - Release ≠ tag; the
releasekeyword is now implemented on top ofglab; release-cli will be removed in 20.0; changelogs rely on trailers, which requirevX.Y.Ztags. - Cleanup policies: a match on any keep rule keeps the tag, and a delete rule must match all criteria to delete;
latestis always kept; protected and immutable tags are skipped. - 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.
- 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
| Order | Object | Why |
|---|---|---|
| 1 | stop review environments, cancel running pipelines, unlock state | stop what is still writing first |
| 2 | (if created) cloud resources: tofu destroy or delete mr-* container apps | stop billing; destroy only knows what to delete while the state still exists |
| 3 | delete managed state, Feature Flags, deployment freezes | dependencies are already gone |
| 4 | restore merge methods, turn off trial feature settings | avoid affecting later lessons |
| 5 | decide what to keep: component projects and Catalog, v1.0 / v1.2.0 Releases, cleanup policies, protected container tags | recommended to keep, lesson 6 adds security scanning components on top of it |
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
Cleanup dependency graph
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.
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
| Command | Object to clean up |
|---|---|
glab api -X POST projects/:id/environments/:eid/stop → DELETE …/environments/:eid | review environments |
glab api -X DELETE projects/:id/environments/review_apps?dry_run=false | bulk delete stopped review environments (API parameters per the docs) |
glab opentofu state delete dev --force -R $INFRA_PROJECT | managed state |
glab api -X DELETE projects/:id/feature_flags/new_counter_ui | flags |
glab api -X DELETE projects/:id/freeze_periods/:fid | deployment freezes |
glab repo delete $DEPLOY_PROJECT --yes | projects no longer needed |
Lab 8: self-assessment + cleanup (about 10 min)
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"
donetofu 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
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
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.
python3 ~/gitlablab/gitlab_ready.py "$GL_PROJECT" run it again; “no leftover review/* environments” should be PASS.glab 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.
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"
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
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.
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.
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.
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.
Command cheat sheet
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_SHAcreate-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)
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{ "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"
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
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
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
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 / error | Most likely cause | First step |
|---|---|---|
Component '…@~latest' - content not found | No published version / wrong path / no permission | glab release list -R component-project |
unknown input arguments: x | Input name misspelled or removed in a new version | Check against the Catalog input table |
| trigger job green, child pipeline red | strategy not set | Add strategy: mirror |
downstream pipeline can not be created … empty | all child job rules are unsatisfied | Use parent_pipeline / $CI_MERGE_REQUEST_ID |
| trigger job stuck on running (depend) | downstream waits on a blocking manual job | Change to mirror or run the manual job |
glab command not found … v1.58.0 | release job image lacks glab | gitlab-org/cli:latest |
| glab release 404 in CI | GITLAB_TOKEN=$CI_JOB_TOKEN | Change to GLAB_ENABLE_CI_AUTOLOGIN |
| changelog requires from | the previous tag is not vX.Y.Z | Pass from=SHA |
| cleanup policy does not delete tags | keep regex / keep_n / older_than / protection rules | Walk through with the evaluator |
| Review environment not stopped | stop job rules inconsistent | same rules + GIT_STRATEGY: none |
| Flag always False | app_name does not match the environment scope | Check production / review/* |
| MR stuck pending (after enabling merged results) | no MR pipeline configured | workflow:rules Add merge_request_event |
Error acquiring the state lock | Lock held / Developer trying to lock | glab 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
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.
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).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.rebase_merge; open two MRs at the same time and experience “needs rebase” before merging (Premium / trial users switch to merge trains).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.next_run_at; the protected container tag rule covers 1.3.0; a Developer pushes :1.3.0 is rejected.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.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.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
Source
| Topic | Source | Verified date | Facts used in this lesson |
|---|---|---|---|
| CI/CD components and Catalog | docs.gitlab.com/ci/components | 2026-11-16 | Directory 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 inputs | docs.gitlab.com/ci/inputs | 2026-11-16 | types 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 pipelines | Downstream pipelines · trigger · Troubleshooting | 2026-11-16 | parent-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-cli | release keyword · Releases · Release CLI (deprecated) · glab release create | 2026-11-16 | release 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) |
| Changelog | Changelogs · Repositories API | 2026-11-16 | trailer 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 registries | cleanup policy · protected container tags · immutable container tags · package storage | 2026-11-16 | 10-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 strategies | Review apps · Incremental rollouts · Feature flags · Feature flags API | 2026-11-16 | Review 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 results | Merge trains · Merged results pipelines · Projects API | 2026-11-16 | Premium / 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 state | IaC with OpenTofu · GitLab-managed state · Deprecations · components/opentofu | 2026-11-16 | OpenTofu 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 |
| Versions | docs.gitlab.com/releases · glab releases | 2026-11-16 | GitLab 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 courses | Terraform 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):
- Talk: Efficient DevSecOps workflows with reusable CI/CD components — GitLab Unfiltered
- NEW GitLab CI CD components explained — Christian Lempa
- Parent-Child Pipelines feature demo — GitLab Unfiltered
- Create child pipelines using dynamically generated configurations — GitLab Unfiltered
- Nested Dynamic Pipelines — GitLab Unfiltered
- Eliminating risk with feature flags — GitLab
- Demo: Cloud Native Development with GitLab — GitLab
- How to avoid broken master with Merge Train — GitLab Unfiltered
- Terraform with GitLab — GitLab Unfiltered
- GitLab CI CD automation (Docker, Kubernetes, Terraform, and more…) — Christian Lempa
- GitLab CI CD Tutorial for Beginners [Crash Course] — TechWorld with Nana
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 argumentsverified 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: mirrorFor 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
inputsis not clearly documented; this lesson therefore passes runtime values via trigger variables,trigger:inputsand 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 listJMESPath 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_enabledand similar parameters on Free follows the actual response. GitLab.com trial terms follow about.gitlab.com. glabThe subcommand output format changes between versions (for exampleglab opentofu state list,glab ci getfields); the examples are for reference only.alpine:3.22,hashicorp/random ~> 3.7are 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.