GitLab Hour 2: GitLab CI/CD Core

Starting from “why one push becomes a pipeline”: .gitlab-ci.yml, rules, variables, Runners, cache and artifacts, include and components, and finally a CI readiness review
GitLab 19.5 (latest patch 19.5.6)GitLab Runner 19.5.3glab 1.130.0All labs can be completed on the Free tierVerified against docs.gitlab.com · 2026-11-16
Overall learning goals
  • Draw the real architecture of GitLab CI/CD: GitLab (Rails + Sidekiq + Workhorse) creates pipelines and jobs → the Runner long-polls and claims jobs → the executor runs them → logs, cache, artifacts and status are reported back, and use it to work out which layer a failure happened in.
  • Independently write out myapp's .gitlab-ci.yml: stages, jobs,image,services,default, and use needs to turn the pipeline into a DAG (directed acyclic graph).
  • Master rules and workflow:rules ’s “first match wins” evaluation rules, and distinguish branch pipelines, merge request pipelines and merged result pipelines (Premium), to avoid duplicate pipelines.
  • Use CI/CD variables correctly: precedence,Protected / Masked / Masked and hidden, File type, and know what they protect and what they do not.
  • Compare GitLab-hosted Runner with self-managed Runner, using glrt- the new authentication-token flow to register in Docker gitlab-runner (tags lab-docker), and choose an executor.
  • Clearly distinguish cache (for speed) from artifacts (to pass results), using include, templates, and CI/CD components to reuse configuration and complete a CI readiness review.

1-hour time allocation table

#TimeModuleCore contentAnimation / interactionLab (project mygroup-lab/myapp)
0Before classWarm-up and bridgeFill in myapp's tests and dependencies, and commit the first .gitlab-ci.ymlCI readiness self-assessment (10 items)First green pipeline
100–06CI/CD architecturePipelines, stages, jobs, Runners, executors; job state machine; hosted vs self-managedCore animation: the lifecycle of one pipeline runReading each stage of a job log
206–13.gitlab-ci.yml syntaxstages, jobs, image, services, default, needs (DAG), parallel:matrixStage order vs DAG Gantt chartlint → test → build, using needs to go faster
313–21rules, workflow and pipeline typesrules:if/changes/exists, workflow:rules, MR pipelines, merged results, duplicate pipelinesrules evaluatorOnly run on MRs and main
421–28Variables and protected variablesPredefined variables, precedence, Protected / Masked / Hidden, File typeVariable precedence resolution + log maskingglab variable set
528–35RunnerGitLab-hosted Runner machine types and compute minutes, self-managed registration (glrt-), executors, tagsJob-to-Runner matching simulatorRunning in Docker gitlab-runner
635–42Cache and artifactscache:key:files, fallback_keys, policy; artifacts, reports, expire_in, dependenciesCache hits / artifact passing across two pipeline runspip cache + JUnit report
742–50include, templates and componentslocal/project/remote/template/component, spec:inputs, CI/CD Cataloginclude merge visualizationAdding the Secret Detection component
850–60CI readiness review and common failuresReview checklist, locating job logs, common errorsFailure log classifier + troubleshooting treeDeliberately trigger 4 kinds of failure and fix them
—After classCheat sheet · Comprehensive labFull myapp CI: MR gate + self-managed Runner building the image and pushing it to the GitLab Container RegistryGraduation quiz (12 questions)Comprehensive lab

Knowledge Coverage Matrix

Target skillM1M2M3M4M5M6M7M8Key commands / keywordsLab
Explain the whole pipeline process, from event to status✓·✓·✓✓·✓glab ci view, job logsM1 lab
Write .gitlab-ci.yml and a DAG·✓···✓✓✓stages,needs,glab ci lintlint/test/build
Control when jobs run (rules / workflow)··✓···✓✓rules:if,CI_PIPELINE_SOURCEMR pipeline
Use variables and secrets safely···✓✓··✓glab variable set -m -pProtected variables
Choose and register a Runner✓···✓✓·✓gitlab-runner register --tokenDocker Runner
Speed up with cache and pass results with artifacts✓✓···✓·✓cache:key:files,artifacts:reportspip cache
Reuse configuration (include / components)······✓✓include:component,spec:inputsSecret Detection
Locate and fix CI failures✓✓✓✓✓✓✓✓glab ci trace,CI_DEBUG_TRACEM8 failure drill

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

TopicWhy it is not in this lessonWhere to learn it
Protected branches, approval rules, push rules, repository mirroringBelongs to repository and collaboration governance, which the Git course coversGit Lesson 4,GitLab Lesson 1
OIDC (id_tokens) deploying to Azure / AWS and pushing container images to cloud registriesNeeds a cloud account, so it is a separate lessonLesson 3 (Azure),Lesson 4 (AWS)
Component development and publishing, parent-child and multi-project pipelines, merge trains, environments and deployment approvalsBelongs to “production-grade pipelines”Lesson 5
Security scan result governance, compliance pipelines, pipeline execution policiesRequires Ultimate; it is a governance topicLesson 6
Runner autoscaling (Docker Autoscaler, Kubernetes executor), performance tuningBeyond 1 hourLesson 7
How to write GitHub Actions / Azure Pipelines / JenkinsThis lesson only covers a conceptual comparisonGitHub Actions core · Azure Pipelines core · Jenkins Pipeline core

How to use this course material

10 pages per module
Principles · diagrams · animations · commands · labs · production cases · troubleshooting · quiz · narration · video. We suggest reading the “Principles” and “Animation” pages first, then doing the “Lab”. The Module 1 animation is the main thread of the whole course; each later module corresponds to one step of it.
Learning progress
A module counts toward progress when the quiz score is 70% or higher, or when you click “Mark module complete”. Progress is saved in this browser (if the browser blocks local storage, it is cleared on refresh).
Chinese narration
The “Narration” page reads the lecture script aloud with the browser's built-in Web Speech API (en-US). If there is no Chinese voice pack, the script can still be read or passed to another TTS tool.
Version notes This course uses GitLab.com (SaaS) as its baseline, verified on 2026-11-16. The latest release is GitLab 19.5 (released 2026-10-15, latest patch 19.5.6); 19.6 has not been released yet, and the release notes page still shows it as Upcoming (a minor version ships on the third Thursday of each month; the next one is 19.6). The latest GitLab Runner is v19.5.3 (2026-11-05); the latest glab is v1.130.0 (2026-11-10). The Free tier includes 400 compute minutes per namespace per month. Merged result pipelines and merge queues require Premium / Ultimate, so this course gives Free-tier alternatives. Differences for Self-Managed instances are marked “Self-Managed” in the text.

Module 0 · Warm-up and bridge: your first .gitlab-ci.yml

Confirm that the mygroup-lab/myapp project from Lesson 1 is available, fill in the tests and dependencies, commit your first pipeline, and see a green check mark
Before class ≈ 12 minglab 1.130 · Git · Python 3.13
Prerequisites (state left by Lesson 1)
  • Completed GitLab Lesson 1: a GitLab.com free account, top-level group mygroup-lab (that is, your ${GL_USER}-lab) group, project mygroup-lab/myapp, with the local clone at ~/gitlablab/myapp; environment variables GL_USER,GL_GROUP,GL_PROJECT are set; glab auth status shows you are logged in.
  • myapp already has: app.py (Flask,/ returns the Redis counter hits as JSON,REDIS_HOST default redis; /healthz added by MR !1, returns plain text ok),requirements.txt,requirements-dev.txt,tests/test_app.py, based on python:3.13-slim , running gunicorn as non-root UID 10001 (0.0.0.0:5000) in the Dockerfile,.gitlab/CODEOWNERS and the MR template.
  • main Protected: Push = No one, merge = Maintainers; all tags (*) are protected, Maintainers only; Issue #2 “Add CI pipeline (pytest + docker build)” remains open (milestone v1.0). This lesson's MR will close it. “Pipelines must succeed” was intentionally left off in Lesson 1 and is turned on in this lesson's comprehensive lab.
  • Local tools: Git,glab, Docker Engine 29 (needed for the self-managed Runner in Module 5; the Ubuntu 24.04 lab machine from the Docker course is fine), Python 3.12+ (optional, only for running tests locally).
  • Cost: All labs in this course run on the Free tier. GitLab-hosted Runners consume compute minutes for each job (the small Linux Runner has a cost factor of 1); the whole course uses about 15–30 minutes. Self-managed Runners do not consume compute minutes.
Branch convention for this course Because main forbids direct pushes, so all labs in this course are done on branch feat/ci-pipeline , and each one corresponds to a draft MR (description Closes #2). Labs in each module keep pushing to this branch. Checks that need a “protected reference” are done with a protected tag (Module 4). When the comprehensive lab ends, merge this MR so the CI configuration first enters main.

Step 1: add the test and tool configuration CI needs

CI can only verify things if the repo has checks that run automatically. Lesson 1 already has unit tests; here we add an integration test that needs a real Redis (Module 2 uses services to run), and add a ruff check. Do not modify app.py and Dockerfile.

cd ~/gitlablab/myapp && git switch main && git pull --ff-only
echo "$GL_PROJECT"                 # should print <your-username>-lab/myapp
git switch -c feat/ci-pipeline

cat > tests/test_redis.py <<'EOF'
import os

import pytest

from app import app

# Only runs when REDIS_HOST is set (provided by the Redis service container in CI)
pytestmark = pytest.mark.skipif("REDIS_HOST" not in os.environ, reason="requires Redis")


def test_hits_increase():
    c = app.test_client()
    first = c.get("/").get_json()["hits"]
    second = c.get("/").get_json()["hits"]
    assert isinstance(first, int)
    assert second == first + 1
EOF

echo "ruff>=0.6" >> requirements-dev.txt

cat > pyproject.toml <<'EOF'
[tool.pytest.ini_options]
pythonpath = ["."]
testpaths = ["tests"]

[tool.ruff]
line-length = 100
EOF
cat requirements-dev.txt; ls tests
-r requirements.txt
pytest>=8
ruff>=0.6
test_app.py  test_redis.py

The Lesson 1 dependency format is flask>=3.1 lower-bound constraints like this. For real projects, generate a full lock file with pip-tools or uv (the lock file is also the best source for the Module 6 cache key). In Lesson 1, the / when Redis is absent, returns "hits": null, so the integration test must run in an environment that has Redis.

Step 2: your first .gitlab-ci.yml (and open a draft MR for Issue #2)

GitLab looks for .gitlab-ci.yml in the project root by default (the path can be changed under Settings → CI/CD → General pipelines). Below is the minimal working version: two stages and two jobs, running on a GitLab-hosted Runner.

stages: [lint, test]

default:
  image: python:3.13-slim      # if image is omitted, the hosted Runner uses ruby:3.1 by default

lint:
  stage: lint
  script:
    - pip install ruff
    - ruff check .

unit-test:
  stage: test
  script:
    - pip install -r requirements-dev.txt
    - pytest -q
glab ci lint                       # server-side syntax check (same as CI Lint in the UI)
git add . && git commit -m "ci: first pipeline"
git push -u origin feat/ci-pipeline
glab mr create -b main -t "Add CI pipeline" -d "Closes #2" -l "type::feature" -m v1.0 --draft -y
glab ci status                     # show the latest pipeline on the current branch
glab ci view                       # interactively view jobs; press Enter to see the log
Validating...
✓ CI/CD YAML is valid!
…
!2 Add CI pipeline (feat/ci-pipeline)
 https://gitlab.com/mygroup-lab/myapp/-/merge_requests/2
(running) • 0m 41s    feat/ci-pipeline    https://gitlab.com/mygroup-lab/myapp/-/pipelines/2104567890
┌ lint ──────── ✓ lint
└ test ──────── ● unit-test
…
(success) • 1m 12s   feat/ci-pipeline

At this point there is no workflow:rules, and the job has no MR rules, so only a branch pipeline runs. Module 3 adds MR pipelines and removes duplicates. The MR number depends on your project (in Lesson 1, /healthz was !1; this example uses !2).

Step 3: CI readiness self-assessment (Module 8 will do it again)

Tick the items your project has “already done”. Results are saved only in this browser.

Connection to the previous lesson Lesson 1 set up the collaboration framework on GitLab (groups, projects, MRs, protected branches). From this lesson on, every MR triggers a pipeline, and Lessons 3 and 4 add OIDC deployment on top of this pipeline.

Module 1 · CI/CD architecture: how pipelines, jobs and Runners work

00:00 – 06:00 · GitLab only decides “what to do”; the Runner “actually does it”. The two are connected only by HTTPS long polling
6 minCore animation★★★★★
Learning goals
  • Describe how the five concepts pipeline, stage, job, Runner and executor relate to each other.
  • Describe one pipeline run in order: event → read and expand the YAML (including include) → evaluate rules to generate jobs → queue → Runner polls and claims → executor runs → upload cache / artifacts → report status back.
  • Know that the Runner pulls jobs, so a self-managed Runner only needs outbound HTTPS and does not need any inbound port opened.
Prerequisites: The MR workflow from Lesson 1; images and containers from the Docker course. Importance:★★★★★ (every later module is one step along this main thread)

What: what GitLab CI/CD is made of

ConceptWhat it isWhere it is defined / runs
PipelineOne CI/CD run containing several jobs, with its own ID, source (CI_PIPELINE_SOURCE) and statusCreated by the GitLab server, based on events and .gitlab-ci.yml .
StageGroups jobs and sets the default execution order. Jobs in the same stage run in parallel, and the next stage starts only after all jobs in the previous stage succeedstages: (default .pre, build, test, deploy,.post)
JobThe smallest unit of execution: a group of script commands + an execution environment (image, variables, cache, artifacts)Any non-reserved top-level key in YAML
RunnerA gitlab-runner program: an agent that requests jobs from GitLab, runs them and reports the results backGitLab-hosted (GitLab.com) or self-managed (your machine / cluster)
ExecutorHow the Runner runs jobs: Docker, Kubernetes, Shell, Instance, Docker Autoscaler, etc.Runner's config.toml

Why: why separate the “control plane” from the “execution plane”

A GitLab instance (GitLab.com or self-managed) only stores configuration, schedules jobs, and stores logs and artifacts. The Runners that actually run the commands can be anywhere: your laptop, an internal data center, or Kubernetes in the cloud. Because the Runner actively pulls jobs from GitLab, a Runner inside a private network only needs outbound access to https://gitlab.com , and it can be deployed next to private resources. This is why GitLab supports “one instance + hundreds or thousands of Runners”.

How: the full lifecycle of one pipeline

  1. Event: push, creating or updating an MR, a scheduled run (schedule), the API, a manual run (web), a trigger token, etc., recorded in CI_PIPELINE_SOURCE.
  2. Read and expand the configuration: a GitLab background job (Sidekiq) reads the .gitlab-ci.yml of that commit and expands include (at most 150, including nested ones; all must be parsed within 30 seconds),extends,!reference, and component inputs $[[ inputs.x ]], then performs syntax validation. Errors fail the pipeline immediately and show “yaml invalid”.
  3. workflow:rules evaluation: decides whether to create this pipeline. If no rule matches, the pipeline is not created.
  4. Job rules evaluation: for each job, check the rules entries in order; the first matching rule decides whether the job joins the pipeline, and its when,allow_failure, and variables; if none match, the job is not added.
  5. Queueing: jobs that can start enter the pending status, waiting for a matching Runner (tags, whether it is protected, whether the project has that Runner enabled).
  6. Runner polling and claiming: the Runner polls every check_interval (3 seconds by default) and calls POST /api/v4/jobs/request, and Workhorse handles this request with long polling (holds for up to 50 seconds by default). When a job is available, it returns the job payload immediately (script, variables, image,CI_JOB_TOKEN).
  7. Executor runs the job: using the Docker executor as an example: pull the job image and helper image → clone the code → restore the cache → download artifacts from dependent jobs → run before_script + script → after_script. Logs stream back incrementally (PATCH /api/v4/jobs/:id/trace).
  8. Cache / artifact upload: the cache is stored on the Runner locally (or in an S3/GCS/Azure distributed cache); artifacts are uploaded to GitLab (POST /api/v4/jobs/:id/artifacts).
  9. Status reporting: the Runner uses PUT /api/v4/jobs/:id to report success or failure. GitLab updates the pipeline status, shows the commit status on the MR, and triggers downstream jobs, notifications and merge checks (“pipeline must succeed”).

Job status:

created (waiting for upstream jobs) → pending (waiting for a Runner) → running → success / failed / canceled; there are also skipped,manual (waiting for someone to click),scheduled (when: delayed),waiting_for_resource (resource_group),preparing.

When: hosted Runner or self-managed Runner

GitLab-hosted Runner (GitLab.com)Self-managed Runner
MaintenanceHandled by GitLab; a fresh temporary VM for each jobYou handle installation, upgrades, scaling and cleanup
BillingConsumes compute minutes (Free: 400 minutes per namespace per month; small Linux factor of 1)Does not consume compute minutes; you pay for the machine yourself
NetworkPublic internet; cannot reach your private networkCan reach your private network, private repositories and databases
Suited toopen-source projects, typical build and test work, getting startedspecial hardware / GPUs / private-network access / large volumes of minutes / compliance isolation

Comparison with similar technologies (see the relevant course)

GitLab CI/CDGitHub ActionsAzure PipelinesJenkins
Config fileone .gitlab-ci.yml at the root (can be included).github/workflows/*.yml Multiple workflowsazure-pipelines.ymlJenkinsfile (Groovy DSL)
Execution agentRunner (pull)Runner (pull)Agent (pull)Agent (controller schedules; inbound or outbound JNLP)
Reuse unitinclude, CI/CD componentsActions, reusable workflowstemplatesShared Library
Dependency graphstages + needsneedsdependsOnstage order + parallel
Common misconceptions① “GitLab connects out to the Runner to run commands”: no. The Runner pulls, and GitLab never initiates a connection to a Runner. ② “All jobs in the same pipeline run on the same machine”: each job may be run by a different Runner and a different container, so jobs can only share files through artifacts (reliable) or cache (best effort). ③ “Stages are required”: with needs , jobs can start early across stages (Module 2).

Architecture diagram: GitLab control plane and Runner execution plane

GitLab instance (GitLab.com / self-managed) Git repository (Gitaly)push / MR events SidekiqCreatePipelineServiceExpand include, evaluate rules PostgreSQLpipelines / builds Job queue (pending builds)Match Runners by tags / protected / scopeRunner claims it → running Workhorse + Rails APIPOST /api/v4/jobs/request (long poll ≤50s)PATCH trace · POST artifacts · PUT job Object storageJob log archives, artifacts, Container Registry MR / commit status / notifications“Pipeline must succeed” merge check Runner host gitlab-runner processconfig.toml: token glrt-… · tags Executor (Docker)helper container: clone / cache / artifactsbuild container: image + script Local cacheDocker volume / or S3 distributed cache Outbound HTTPS
Figure 1-1: the Runner only needs outbound HTTPS. It requests jobs from GitLab and uploads logs and artifacts; GitLab never connects to the Runner

Sequence diagram: API round trip for one job

gitlab-runnerGitLab (Workhorse / API)Executor container POST /jobs/request (token glrt-…) 201 job payload / 204 no job (after long poll) Create helper + build containers, clone, restore cache, download artifacts stdout / stderr stream PATCH /jobs/:id/trace (incremental log) Save cache, package artifacts POST /jobs/:id/artifacts (CI_JOB_TOKEN) PUT /jobs/:id state=success|failed
Figure 1-2: all Runner communication consists of HTTPS requests the Runner initiates; during the job it uses short-lived CI_JOB_TOKEN

Core animation: the lifecycle of one pipeline run

Choose the trigger event and environment conditions, then play step by step. The 9 boxes above correspond to 9 real steps; the terminal below shows what you can see in the GitLab UI, the API or the job log. Try changing “Runner tags” to a non-matching value to see why the job gets stuck in pending.

Core commands and arguments

CommandPurposeKey arguments / notes
glab ci lintValidate YAML with server-side rules (including include expansion)--dry-run --ref main Simulated creation; --include-jobs lists the jobs that would be generated
glab ci statusStatus of the latest pipeline on the current branch-b branch,--live live refresh
glab ci viewInteractively view pipelines, jobs and logsJobs can be retried or cancelled in the UI
glab ci listList pipelines--status failed,--source merge_request_event
glab ci traceFollow the log of a jobjob name or ID
glab ci runManually create a pipeline (source api)-b main,--variables KEY:VALUE,--mr
glab ci retry / cancelRetry / cancel a job or pipelineRequires the Developer role or higher
glab ci lint --dry-run --ref main --include-jobs
glab ci list --per-page 5
glab api "projects/:id/pipelines?per_page=1" | python3 -m json.tool | head -20
Validating...
✓ CI/CD YAML is valid!
Jobs:
lint
unit-test
State   IID   Ref    Created
(success) • #12  main  (about 5 minutes ago)
[
    {
        "id": 2104567890,
        "iid": 12,
        "project_id": 61234567,
        "sha": "8f3c2a1…",
        "ref": "main",
        "status": "success",
        "source": "push",
        …

How to verify:source The field is the CI_PIPELINE_SOURCE in the job. Common mistake:glab ci lint By default, validation uses the .gitlab-ci.yml in the current directory, but the local files are read from the server's default branch version. If you changed an included file and have not pushed it yet, the result may differ from what you expect; use --dry-run --ref your-branch for a more accurate result.

Corresponding UI entry

  • Build → Pipeline editor: edit, validate, visualize, and view the “Full configuration” (the result after include expansion).
  • Build → Pipelines / Build → Jobs: status, logs, retry. “Clear Runner cache” is in the more actions menu on the pipeline page.

Lab 1: read one real run along its lifecycle (about 5 minutes)

Manually trigger a pipeline (source api), and note the pipeline ID:
cd ~/gitlablab/myapp
glab ci run -b feat/ci-pipeline
glab ci status --live      # Ctrl+C to exit
Look at the log sections of a job (each section corresponds to one step in the animation):
glab ci trace unit-test | grep -E "^Running with|^Preparing|^Getting source|^Executing|^Cleaning|^Job (succeeded|failed)|Using Docker executor|Runner"
Running with gitlab-runner 19.5.x (…)
  on green-3.saas-linux-small-amd64.runners-manager.gitlab.com/default …
Preparing the "docker+machine" executor
Using Docker executor with image python:3.13-slim ...
Preparing environment
Getting source from Git repository
Executing "step_script" stage of the job script
Cleaning up project directory and file based variables
Job succeeded

The first line of the log tells you which Runner version and which Runner instance ran the job. The hosted Runner's executor name and internal implementation may change over time, so trust the log.

Use the API to look at job metadata (status timeline, Runner, duration):
PIPE=$(glab api "projects/:id/pipelines?per_page=1" | python3 -c 'import sys,json;print(json.load(sys.stdin)[0]["id"])')
glab api "projects/:id/pipelines/$PIPE/jobs" | python3 -c '
import sys,json
for j in json.load(sys.stdin):
    print(j["name"], j["status"], j["queued_duration"], j["duration"], (j.get("runner") or {}).get("description"))'
unit-test success 1.8 38.2 3-green.saas-linux-small-amd64.runners-manager.gitlab.com
lint success 2.4 21.7 1-green.saas-linux-small-amd64.runners-manager.gitlab.com

queued_duration is the number of seconds the job waited in pending for a Runner. A high value means too few Runners or a tag mismatch; duration high means the job itself is slow (Module 6 optimizes it with cache).

Observe “no Runner available”: In .gitlab-ci.yml unit-test job, add tags: [no-such-tag] and push. The job will stay in pending, and the page shows “This job is stuck because you don't have any active runners online or available with any of these tags assigned to them”. After observing this, delete the line and push again.

Case 1: integration test against an internal database

Problem: The integration test needs a test database that is only reachable from the internal network, and the hosted Runner cannot connect to it. Approach: Deploy a self-managed Runner inside the internal network (open only outbound 443 to gitlab.com) and tag it intranet, so only the integration-test job uses this tag. Configuration:tags: [intranet]; set the Runner to “protected”, so it only runs jobs on protected branches. Limitations: the Runner host becomes an attack surface. Anyone who can modify .gitlab-ci.yml can run commands on it; see the security recommendations in Module 5.

Case 2: many jobs pending, and the team wrongly thinks “GitLab is slow”

Problem: During peak hours, jobs wait in the queue for 6 minutes on average. Approach: Use the job API's queued_duration to analyze, and find that the self-managed Runner's concurrent = 1 (it can only run one job at a time). Configuration: Set concurrent to match the number of CPU cores, and give long-running jobs their own Runner. Limitations: As concurrency goes up, disk and Docker image cache grow faster and need regular cleanup (Lesson 7).

Case 3: the MR shows “pipeline must succeed” but can never be merged

Problem: After the developer pushed, there is no pipeline on the MR, and the merge button is grey. Approach: Check Build → Pipelines, and find that the pipeline was never created at all —workflow:rules only allows merge_request_event, but the project has no MR pipeline rules, so “pipeline must succeed” waits forever. Fix: Add the MR event to the rules in Module 3. Lesson learned:“No pipeline” and “pipeline failed” are two different problems. The former is in the configuration / rules layer; the latter is in the execution layer.

Common errors and fixes

This job is stuck because you don't have any active runners online or available with any of these tags assigned to them: lab-docker

Cause: No online Runner meets all of these at once: it is enabled for the project, its tags include all of the job's tags, and its protection settings allow this branch.

glab api "projects/:id/runners?type=project_type" | python3 -m json.tool | grep -E '"(description|status|online|paused)"'
docker exec gitlab-runner gitlab-runner verify

Fix: start or re-register the Runner; add the missing tags in the Runner settings; or remove the job's tags so that the hosted Runner runs it.

yaml invalid / jobs:unit-test config contains unknown keys: scripts

Cause: The pipeline failed at step 2, “Read and expand the configuration”, so it failed immediately and no job ran.

glab ci lint

Fix: correct the keyword as the message says (it should be script). Enabling the GitLab CI JSON Schema in your IDE catches this earlier.

No pipeline appears after a push (the Pipelines page is empty)

Cause: the file name is wrong (it must be .gitlab-ci.yml, or the path set in settings),workflow:rules no rules match, the commit message contains [skip ci], or CI/CD is turned off for the project (Settings → General → Visibility → CI/CD).

git log -1 --format=%B | grep -i "skip ci"
glab ci lint --dry-run --ref "$(git branch --show-current)"
ERROR: Job failed: execution took longer than 1h0m0s seconds

Cause: The project's default job timeout is 1 hour (Settings → CI/CD → General pipelines → Timeout), and Runners can also set a maximum timeout. Jobs on GitLab.com hosted Runners last at most 3 hours regardless of project settings.

Fix: find the command that is stuck (common causes: interactive prompts, waiting on the network). If you really need more time, write timeout: 90m in the job (it cannot exceed the Runner's maximum timeout).

There has been a runner system failure, please try again

Cause: a Runner-side failure (disk full, Docker daemon problem, helper image pull failure), not a problem with your script.

docker logs --tail 50 gitlab-runner
df -h /var/lib/docker

Fix: fix the Runner host and retry. For this kind of failure you can set retry: {max: 2, when: [runner_system_failure, stuck_or_timeout_failure]}.

Command-line questions
1. Without pushing any code, check which jobs the configuration on the feature/x branch would generate.
glab ci lint --dry-run --ref feature/x --include-jobs
2. List the 5 most recent failed pipelines.
glab ci list --status failed --per-page 5
Scenario analysis
The company firewall blocks all inbound connections, and the security team asks: “The self-managed Runner is inside the internal network. How does GitLab.com push jobs to it?” How do you answer?

GitLab does not push jobs. The Runner calls POST /api/v4/jobs/request over outbound HTTPS to request jobs (long polling); logs, artifacts and status are also requests initiated by the Runner. So you only need to allow outbound access to gitlab.com:443 (plus any addresses the jobs need, such as the image registry). No inbound port is needed.

Verified teaching videos

▶
GitLab CI CD Tutorial for Beginners [Crash Course] — TechWorld with Nana
English · full introduction from architecture and Runners to pipelines. Recorded earlier, so the UI and registration flow follow this lesson
▶
GitLab CI CD Pipeline Tutorial | Introduction | 2022 — Moss
English · short video on basic pipeline concepts

Official docs

Video storyboard script (about 90 seconds)

This course page cannot generate video or MP3 directly. Storyboards and narration scripts are provided and can be given to a video tool.

Shot 1 · 0–15s
Visual: a developer runs git push, and a beam of light flies from the laptop to the GitLab building.
Narration: every push is an event. GitLab reads the .gitlab-ci.yml in that commit.
Shot 2 · 15–35s
Visual: the YAML file expands, included files snap in like puzzle pieces, pass through a rules gate, and some jobs are filtered out.
Narration: expand the includes first, then use the rules to decide which jobs enter this pipeline.
Shot 3 · 35–60s
Visual: job cards line up in a queue. In the distance a Runner raises its hand every few seconds asking “Any work?”, and takes a card tagged lab-docker.
Narration: the Runner pulls jobs, and claims one only when the tags match. GitLab never connects to a Runner.
Shot 4 · 60–90s
Visual: containers start, code is cloned, cache is restored, tests run; logs stream back to GitLab, artifacts upload, and a green check mark appears on the MR.
Narration: when execution finishes, the Runner uploads logs, cache and artifacts and reports the status. Only then can the MR be merged.
or score ≥ 70% in the quiz

Module 2 · .gitlab-ci.yml syntax: stages, jobs and needs (DAG)

06:00 – 13:00 · stages give the “default order”; needs draws the “real dependencies”. The total pipeline duration is set by the longest dependency chain
7 minFree★★★★★
Learning goals
  • Write a configuration that includes stages,default,image,services,variables,script .
  • Use extends, hidden jobs (starting with . ),!reference and YAML anchors to reduce repetition.
  • Use needs to build a DAG and understand its effect on execution order and artifact downloads; learn to use parallel:matrix for fan-out.
Prerequisites: Basic YAML syntax; the job lifecycle from Module 1. Importance:★★★★★

What: the structure of the file. The top level of

.gitlab-ci.yml has only two kinds of keys: Global keywords (stages,default,include,variables,workflow, and the header block of component files ( spec) and jobs (any other name). A job whose name starts with . is a hidden job: it does not run and is usually used as a template.

KeywordPurposeKey points
stagesDefines the stage orderIf not defined, the default is .pre, build, test, deploy, .post; if a job does not write stage , it belongs to test
defaultdefault values for jobsCan set image,services,before_script,after_script,cache,artifacts,tags,retry,interruptible,hooks,id_tokens , etc. If a job writes a keyword with the same name, it completely overrides it (no merging)
scriptRequired; shell commands run line by line; a non-zero exit code on any line fails the job; before_script and script run in the same shell.
after_scriptCleanup commandsrun in a separate shell, even if the job fails or is cancelled, and cannot see script variables exported in it.
image / servicesJob container image / sidecar containersOnly applies to container-based executors such as Docker and Kubernetes; service containers default to using the image name as the hostname (redis:8 → redis), and you can use alias to rename them
needsDeclare job dependencies and skip the stage waitUp to 50 (GitLab.com); can depend on jobs in the same stage; needs: [] means the job starts immediately after the pipeline is created.
extendsInherit from other jobs (including hidden jobs)Hashes are deep-merged, arrays are replaced as a whole; up to 11 levels of nesting
parallel / parallel:matrixParallel copies / matrix fan-outparallel Values 1–200; matrix combinations must not exceed 200
allow_failure,retry,timeout,interruptibleFailure tolerance, automatic retry (max 0–2), timeout, and whether it can be cancelled when a new commit is pushedretry:when Can retry only runner_system_failure and similar infrastructure errors

Why: why needs is needed

When running by stage, the next stage waits until all jobs in the previous stage finish. A 4-minute integration test holds up an image build that only depends on the unit tests. needs Writing down exactly what you depend on lets GitLab draw the DAG: each job starts as soon as its dependencies finish, and the total pipeline duration shrinks to the length of the critical path.

How: the two effects of needs

  1. Execution order: a job only waits for needs (and their dependencies), instead of waiting for the whole previous stage.
  2. Artifact downloads: jobs with needs only download needs artifacts of the jobs in needs:artifacts (default true); jobs without needs download artifacts from all earlier stages by default (can be limited with dependencies ).

Other details: needs:optional: true A job that is depended on may be left out of the pipeline by rules. If a depended-on job is not in the pipeline and is not optional, pipeline creation fails with an error. needs:pipeline:job Artifacts can be fetched from a parent pipeline (Lesson 5). needs:project Fetching artifacts across projects requires Premium.

When: stages or needs

  • Small projects: stages are enough and easy to read.
  • Multi-language / monorepo / long-running jobs: use needs, and keep stages as visual grouping.
  • Checks that only need to start as soon as possible (lint, secret detection): needs: [].

Comparison with similar technologies

GitLabGitHub ActionsAzure PipelinesJenkins
Dependency relationshipsneeds: [job]needs: jobdependsOnstage order + parallel block
Template inheritanceextends,!reference, anchorsreusable workflows, composite Actionstemplate Parameterizationshared library functions
Matrixparallel:matrixstrategy.matrixstrategy: matrixmatrix directive
service containersservicesservicesservices (container resources)plugins / hand-written docker run
Common misconceptions① “default “The before_script in default is merged with the job's before_script — no. A job's value replaces the default as a whole; to merge, use !reference [default, before_script]. ② “needs only affects order”: it also decides which artifacts are downloaded. When a “file is missing” problem shows up after adding needs , this is usually the cause. ③ “In script , after cd , after_script the current directory is still the same”—after_script is a new shell that starts in the project directory.

Same pipeline: by stage vs DAG

By stage (no needs): the next stage waits until all jobs in the previous stage finish lint 1m unit-test 2m integration 4m build-image 3m scan-image 2m Critical path 1+4+3+2 = 10 minutes DAG (needs): each job waits only for the jobs it truly depends on lint unit-test integration build-image scan-image Critical path 1+2+3+2 = 8 minutes integration runs in parallel and only needs to finish
Figure 2-1: needs lets build-image wait only for unit-test, so it is no longer held up by the 4-minute integration test

Inheritance and reuse: extends, !reference, default

default:image: python:3.13-slimbefore_script: [pip install …]interruptible: true .python-job: (hidden job)variables: {PIP_…: …}cache: {key: …, paths: […]} unit-test: extends: .python-jobhashes (variables, cache) → deep mergearrays (script, before_script) → replaced as a wholethe job's own value > extends value > defaultTo concatenate arrays:- !reference [.python-job, before_script]
Figure 2-2: the merged result can be seen in the “Full configuration” of the pipeline editor

Interactive Gantt chart: add needs to a job and see how the total duration changes

Tick a job's needs option, and the Gantt chart recalculates each job's start time in real time (unit: minutes). Red jobs are on the critical path. The terminal shows the equivalent YAML snippet.

Quick reference for common keywords

SyntaxPurposeNotes
needs: [lint]Only wait for lintAlso download only lint's artifacts
needs: []Start immediatelyWait for no job and download no artifacts
needs: [{job: build, artifacts: false}]Wait but do not download artifactsReduces download time
needs: [{job: docs, optional: true}]Depend on an optional jobNo error when docs is excluded by rules
parallel: {matrix: [{PY: ["3.12","3.13"]}]}Matrix fan-outjob name will include [3.12] and similar suffixes
services: [{name: redis:8, alias: cache}]Sidecar containerreach it via an alias in the job cache access
retry: {max: 2, when: [runner_system_failure]}Retry only infrastructure errorsDo not hide flaky tests
interruptible: trueCan be cancelled automatically when a new commit is pushedUse with workflow:auto_cancel (Module 3)
# Validate, and view the jobs that would be generated
glab ci lint --dry-run --ref main --include-jobs
# In the UI: Build → Pipeline editor → the “Visualize” tab shows the DAG; “Full configuration” shows the merged result
Validating...
✓ CI/CD YAML is valid!
Jobs:
lint
unit-test: [3.12]
unit-test: [3.13]
integration-test
build-image

Common mistake:needs Referencing a job that rules excluded makes pipeline creation fail: 'build-image' job needs 'unit-test' job, but 'unit-test' does not exist in the pipeline. Fix: align the rules on both sides, or use optional: true.

Lab 2: lint → test → build, then speed it up with needs (about 6 minutes)

Write a complete three-stage pipeline:
stages: [lint, test, build]

default:
  image: python:3.13-slim
  interruptible: true

variables:
  PIP_DISABLE_PIP_VERSION_CHECK: "1"

.python-job:
  before_script:
    - pip install -q -r requirements-dev.txt

lint:
  stage: lint
  needs: []
  script:
    - pip install -q ruff
    - ruff check .

unit-test:
  stage: test
  extends: .python-job
  needs: [lint]
  parallel:
    matrix:
      - PY: ["3.12", "3.13"]
  image: python:${PY}-slim
  script:
    - pytest -q tests/test_app.py

integration-test:
  stage: test
  extends: .python-job
  needs: [lint]
  services:
    - name: redis:8
      alias: redis
  variables:
    REDIS_HOST: redis
  script:
    - pytest -q tests/test_redis.py

build-image:
  stage: build
  image: docker:29
  services: [docker:29-dind]
  variables:
    DOCKER_TLS_CERTDIR: "/certs"
  needs: ["unit-test"]
  script:
    - docker build -t myapp:$CI_COMMIT_SHORT_SHA .
    - docker run --rm myapp:$CI_COMMIT_SHORT_SHA python -c "import app; print('import ok')"
glab ci lint --dry-run --ref main --include-jobs
git add .gitlab-ci.yml && git commit -m "ci: stages + needs DAG" && git push
glab ci view

needs: ["unit-test"] waits for both copies produced by the matrix at the same time. build-image On hosted Runners you can use Docker-in-Docker (hosted Runners run in privileged mode); on self-managed Runners you need privileged = true (Module 5).

Observe the DAG: on the MR or pipeline page, switch to the “Job dependencies” view, which shows the dependency lines. Compare build-image's start time with integration-test's end time.
lint                  00:00 → 00:35
unit-test: [3.12]     00:36 → 01:30
unit-test: [3.13]     00:36 → 01:28
integration-test      00:36 → 02:05
build-image           01:31 → 02:40   # does not wait for integration-test
Experience default overriding: in integration-test add before_script: [echo hi], and after pushing you find the dependencies not installed and the tests failing — the job's before_script completely replaced .python-job . Fix:
  before_script:
    - !reference [.python-job, before_script]
    - echo hi

Case 1: monorepo pipeline 45 minutes → 18 minutes

Problem: Frontend, backend and docs live in one repository, with three stages running in series, so any slow job drags everything down. Approach: Use needs to chain each sub-project's build → test → package into an independent chain. Combined with Module 3's rules:changes so that only the affected chains run. Limitations: jobs referenced by needs must be in the pipeline, or creation fails. For jobs that changes may exclude, use optional: true.

Case 2: an intermittent failure caused by a service container port conflict

Problem: Two jobs running concurrently on a Shell executor both start Redis on the host, and port 6379 conflicts. Approach: Switch to the Docker executor + services, so each job has its own network namespace. Lesson learned: Under the Shell executor, services has no effect. Jobs that depend on the host environment are inherently not isolated.

Case 3: matrix testing across multiple Python versions

Approach:parallel:matrix + image: python:${PY}-slim. Limitations: matrix variables can be used in image,services,tags and so on, but job names become unit-test: [3.12]. To refer to the whole matrix in needs , write unit-test; to refer to a single copy, you need needs:parallel:matrix.

Common errors and fixes

jobs:build-image:needs config uses invalid job: unit-tests

Cause: a job name in needs is misspelled or does not exist.

glab ci lint --dry-run --ref main --include-jobs

Fix: correct the name by checking the job list.

'build-image' job needs 'unit-test' job, but 'unit-test' does not exist in the pipeline. This might be because of the only, except, or rules keywords.

Cause: the depended-on job was not added to this pipeline by rules (for example, it only runs in MRs).

Fix: make the rules match on both sides, or write needs: [{job: unit-test, optional: true}].

redis.exceptions.ConnectionError: Error -2 connecting to redis:6379. Name or service not known.

Cause: did not declare services, the service alias is wrong, or the job runs on a Shell executor (services are not supported).

Fix: confirm that services: [{name: redis:8, alias: redis}] and REDIS_HOST match. Check the start of the job log for “Starting service redis:8 …”. If the service starts slowly, wait for it to be ready in the script.

error during connect: Get "http://docker:2375/v1.xx/info": dial tcp: lookup docker … no such host

Cause: using a docker image but without a docker:29-dind service, or inconsistent TLS variables.

Fix: add the dind service and set DOCKER_TLS_CERTDIR: "/certs"; a self-managed Runner needs privileged = true and must mount /certs/client (Module 5).

This GitLab CI configuration is invalid: jobs:unit-test:parallel:matrix config should be an array of hashes

Cause: matrix was written as a hash instead of an array.

Fix: write it as matrix: [ {PY: ["3.12","3.13"]} ] (each array element is one combination of variable values).

Command-line questions
1. Write the skeleton of a secret-check job that starts immediately and downloads no artifacts.
secret-scan:
  stage: lint
  needs: []
  script: [echo "scan"]
2. Make a job retry at most 2 times, and only on Runner system failures.
retry:
  max: 2
  when: [runner_system_failure, stuck_or_timeout_failure]
Scenario analysis
After adding needs: [build-image] to the deploy job, deploy fails because it cannot find dist/, but dist/ is an artifact of the compile job. Why?

Jobs that use needs only download the artifacts of the jobs listed in needs . deploy depends only on build-image, so it cannot get compile's artifacts. Fix: add needs: [build-image, compile] (if you don't want to wait, control this with the artifacts option), or have build-image pass the files it needs on as artifacts.

Verified teaching videos

▶
Gitlab CI pipeline tutorial for beginners — Valentin Despa
English · writing .gitlab-ci.yml from scratch: stages, jobs, artifacts
▶
DevOps with GitLab CI Course - Build Pipelines and Deploy to AWS — freeCodeCamp.org
English · long, complete course; the first half covers syntax, needs and artifacts. The deployment part corresponds to Lesson 4 of this series
▶
Parent-Child Pipelines feature demo — GitLab Unfiltered
English · demo referenced in the official docs, for further reading (covered in depth in Lesson 5)

Official docs

Video storyboard script (about 90 seconds)

Shot 1 · 0–20s
Visual: three columns of stage boxes; job cards queue up by column, and a long 4-minute card in the second column flashes.
Narration: when running by stage, the next column must wait until the previous column finishes, and the slowest job sets the pace.
Shot 2 · 20–50s
Visual: an arrow is drawn from build-image that connects only to unit-test; the cards slide left and the Gantt chart shortens.
Narration: needs spells out the real dependencies. Jobs start as soon as their dependencies finish, and the total duration equals the critical path.
Shot 3 · 50–75s
Visual: artifact packages travel along the needs arrows; jobs without an arrow do not get a package.
Narration: needs also decides whose artifacts get downloaded. This is the most common cause of “the file is missing”.
Shot 4 · 75–90s
Visual: one job card is copied into two cards, for 3.12 and 3.13.
Narration: a parallel matrix tests multiple versions with one block of configuration.
or score ≥ 70% in the quiz

Module 3 · rules, workflow and pipeline types (branch / MR / merged result)

13:00 – 21:00 · workflow:rules decides “whether this pipeline exists”; job rules decide “which jobs are in the pipeline”. Both use first-match-wins
8 minrules / workflow: Freemerged result pipelines / merge trains: Premium★★★★★
Learning goals
  • Write rules:if,rules:changes (including compare_to),rules:exists, and explain the evaluation rules: “first match” and “no match means not added”.
  • Distinguish branch pipelines, tag pipelines, MR pipelines (detached), merged result pipelines (merged_result) and merge trains (merge_train).
  • Use the officially recommended workflow:rules to avoid “two pipelines per push”, and use workflow:auto_cancel to cancel outdated pipelines.
Prerequisites: steps 3 and 4 of the Module 1 lifecycle; the MR workflow from Lesson 1. Importance:★★★★★

What: what rules are made of

Each rule contains at least one of if,changes,exists,when , and can also set allow_failure,needs,variables,interruptible. Multiple conditions in one rule are combined with and.

ClauseWhat it checksExample
ifVariable expression: ==,!=,=~ (regex),!~,&&,||, parentheses; an undefined variable is treated as null$CI_COMMIT_BRANCH == $CI_DEFAULT_BRANCH
changesWhether the files changed in this push match (up to 50 patterns per clause)changes: {paths: ["**/*.py"], compare_to: refs/heads/main}
existsWhether a file exists in the repositoryexists: [Dockerfile]
whenHow the job joins after a matchon_success (default),manual,delayed,always,never

How: evaluation rules (must memorize)

  1. Check rules in order; the first matching rule takes effect; the rest are not checked.
  2. The when of the matching rule is never → the job is not added; any other value (or not written) → the job is added and uses that rule's attributes.
  3. If no rule matches → the job is not added to the pipeline.
  4. The when: manual in rules defaults to allow_failure: false (it blocks later stages and “pipeline must succeed”); when not written in rules, when: manual defaults to allow_failure: true.
  5. changes comparison target: for a branch push, it compares before and after the push; for MR pipelines, it compares the source and target branches; For the first push of a new branch and for pipelines without a push event (scheduled, manual, API), changes always evaluates to true, unless compare_to is set.

workflow:rules Uses the same syntax, but applies to the whole pipeline. when can only be always or never; if no rule matches, the pipeline is not created. workflow:name Names the pipeline (up to 255 characters); workflow:auto_cancel:on_new_commit values of conservative (default; cancels only when no interruptible: false job has started yet),interruptible (only cancels interruptible jobs),none.

Pipeline types

TypeWhen it is createdCI_PIPELINE_SOURCECode under testLevel
Branch pipelinePush to a branchpushLatest commit on the branchFree
Tag pipelinePush a tagpush (CI_COMMIT_TAG has a value)Commit the tag points toFree
MR pipelineCreated / updated MR, and the configuration has rules for MRsmerge_request_event,CI_MERGE_REQUEST_EVENT_TYPE=detachedLatest commit on the source branchFree
Merged result pipelineSame as above, with Enable merged results pipelines turned on in Settings → Merge requestsmerge_request_event,merged_resultSource and target branches'temporary merge commit (falls back to a regular MR pipeline on conflict)Premium / Ultimate
Merge trainMR joins the merge trainmerge_request_event,merge_traintarget branch + all earlier MRs in the queue + this MRPremium / Ultimate
OtherScheduled, manual, API, trigger token, parent-child / multi-projectschedule,web,api,trigger,parent_pipeline,pipelineSpecified refFree

Why: why two pipelines appear

If a job's rules allow push and also allow merge_request_event, a single push to a branch that has an open MR creates both a branch pipeline and an MR pipeline, wasting compute minutes and making the MR page messy. The officially recommended workflow:rules:

workflow:
  rules:
    - if: $CI_PIPELINE_SOURCE == "merge_request_event"   # 1) MR pipeline
    - if: $CI_COMMIT_BRANCH && $CI_OPEN_MERGE_REQUESTS   # 2) the branch already has an open MR → no more branch pipelines
      when: never
    - if: $CI_COMMIT_BRANCH                               # 3) pushes to other branches

Note: this rule does not cover tags or scheduled runs; append them when needed - if: $CI_COMMIT_TAG,- if: $CI_PIPELINE_SOURCE == "schedule". CI_OPEN_MERGE_REQUESTS is a list of up to 4 open MRs whose source branch is this branch.

When: which one to choose

  • Free-tier teams: MR pipelines + protected main + “pipeline must succeed”; require the branch to be rebased before merging (Settings → Merge requests → merge method “Fast-forward merge”) to approximate testing the merged result.
  • Premium: enable merged result pipelines; for a trunk with frequent merges, also enable merge trains (Lesson 5).
  • only / except is legacy syntax, no longer actively developed, and cannot be mixed in the same job with rules — new configurations should always use rules.

Comparison with similar technologies

GitLabGitHub ActionsAzure PipelinesJenkins
Trigger conditionsworkflow:rules + CI_PIPELINE_SOURCEon: push / pull_requesttrigger / prMultibranch scan + webhook
Job conditionsrulesif:condition:when { }
Tests the merged codeMerged result pipelines (Premium)pull_request Checks out the merge commit by defaultPR builds use the merge commit by defaultMerge strategy of the branch source plugin
Common misconceptions① “rules are all checked and the strictest result wins”: no. Evaluation stops at the first match, so when: never exclusion rules must come first. ② “changes in a scheduled run only looks at recent changes”: when there is no push event, changes always evaluates to true. ③ “Having an MR pipeline makes the branch pipeline disappear automatically”: it only disappears with the workflow:rules above. ④ “The Free tier can also test merged results”: merged result pipelines require Premium.

Evaluation flow: from event to job list

Eventpush / MR / schedule workflow:rulesFirst match: always → continuenever / no match → not created No pipeline Evaluate rules job by job Rule 1 matches? → use its when No → does rule 2 match? … rule n No match at all → job not added Result on_success → createdmanual → waits for someone to click (allow_failure: false)delayed → scheduledalways → runs even if earlier jobs failednever → not addedZero jobs → pipeline creation fails
Figure 3-1: two layers of filtering. First decide the pipeline, then decide the jobs; both layers use “first match wins”

Which code the MR pipeline tests

main M, just merged by someone else feature/login F2 (latest on the source branch) Temporary merge commit(merged result pipeline) The MR pipeline (detached) tests only F2. The merged result pipeline tests the merge of F2 + M, which can catch “each green alone, red together” early.
Figure 3-2: the commit tested by a merged result pipeline (Premium) exists on no branch; it is visible only in the pipeline details

Interactive evaluator: which jobs does this event produce?

Set the event parameters; the evaluator checks the real rules one by one workflow:rules and each job's rules, highlighting the first matching rule. Turn off “Use workflow:rules” to reproduce duplicate pipelines.

Common rule patterns

Requirementrules
Only on the default branch- if: $CI_COMMIT_BRANCH == $CI_DEFAULT_BRANCH
Only in MRs- if: $CI_PIPELINE_SOURCE == "merge_request_event"
Only on semantic version tags- if: $CI_COMMIT_TAG =~ /^v\d+\.\d+\.\d+$/
Draft MRs skip heavy jobs- if: $CI_MERGE_REQUEST_DRAFT == "true" + when: never (put it first)
Only when Python files change- changes: {paths: ["**/*.py", "requirements*.txt"], compare_to: refs/heads/main}
Only build when a Dockerfile exists- exists: [Dockerfile]
Manual deploy on main- if: $CI_COMMIT_BRANCH == "main" + when: manual
Set a variable in a rulevariables: {DEPLOY_ENV: production}
# Simulate which jobs an MR pipeline would generate (requires an existing MR)
glab mr create --fill --source-branch feature/rules --target-branch main --yes
glab ci run --mr             # manually create an MR pipeline for the current branch's MR
glab ci list --source merge_request_event --per-page 3
# Print key variables in a job to verify which rule matched
echo "$CI_PIPELINE_SOURCE $CI_MERGE_REQUEST_EVENT_TYPE $CI_COMMIT_BRANCH $CI_OPEN_MERGE_REQUESTS"
Creating merge request for feature/rules into main in mygroup-lab/myapp
!7 ci: rules demo (feature/rules)
 https://gitlab.com/mygroup-lab/myapp/-/merge_requests/7
…
merge_request_event detached  

In an MR pipeline, CI_COMMIT_BRANCH is empty (you should use CI_MERGE_REQUEST_SOURCE_BRANCH_NAME), which is exactly why the workflow rules above can tell the two kinds of pipelines apart.

Lab 3: run only on MRs and main, and eliminate duplicate pipelines (about 7 minutes)

First reproduce the duplicate pipeline: add a rule to unit-test that allows both push and MR (without workflow):
unit-test:
  rules:
    - if: $CI_PIPELINE_SOURCE == "merge_request_event"
    - if: $CI_COMMIT_BRANCH
cd ~/gitlablab/myapp && git switch feat/ci-pipeline
git commit -am "ci: rules demo" && git push      # the branch already has an open draft MR !2
glab ci list -r feat/ci-pipeline --per-page 2
glab ci list --source merge_request_event --per-page 2
(running) • #21  feat/ci-pipeline              ← push (branch pipeline)
(running) • #22  refs/merge-requests/2/head    ← MR pipeline
…

The same commit ran twice: jobs without MR rules (lint) appear only in the branch pipeline, while unit-test runs once in each pipeline.

Add workflow rules and tidy up the job rules:
workflow:
  name: "$CI_PIPELINE_SOURCE · $CI_COMMIT_REF_NAME"
  auto_cancel:
    on_new_commit: interruptible
  rules:
    - if: $CI_PIPELINE_SOURCE == "merge_request_event"
    - if: $CI_COMMIT_BRANCH && $CI_OPEN_MERGE_REQUESTS
      when: never
    - if: $CI_COMMIT_BRANCH
    - if: $CI_COMMIT_TAG
build-image:
  rules:
    - if: $CI_PIPELINE_SOURCE == "merge_request_event"
      changes:
        paths: [Dockerfile, "**/*.py", "requirements*.txt"]
    - if: $CI_COMMIT_BRANCH == $CI_DEFAULT_BRANCH
git commit -am "ci: workflow rules" && git push
glab ci list --per-page 3
(running) • #23  refs/merge-requests/2/head   merge_request_event · feat/ci-pipeline
(canceled) • #22 …   ← interruptible jobs of the old commit were cancelled automatically

This time there is only one MR pipeline. Job rules and workflow rules are two layers of filtering; a job appears only if it passes both. Jobs without rules (lint) appear in every pipeline that is created.

Verify changes: push a README-only change, and build-image does not appear in the MR pipeline. After the MR is merged, the pipeline on main will include it.
echo "docs" >> README.md && git commit -am "docs only" && git push
glab ci lint --dry-run --ref feat/ci-pipeline --include-jobs

--dry-run This simulates a branch pipeline, not an MR pipeline; the MR's job list on the MR page is authoritative.

(optional Premium trial) Settings → Merge requests → Merge options → tick “Enable merged results pipelines”, then push once more; the printed CI_MERGE_REQUEST_EVENT_TYPE becomes merged_result. The Free tier skips this step.
Wrap-up: Do not merge the draft MR !2. Later modules keep working on feat/ci-pipeline and merge it at the end of the comprehensive lab (turn on “pipeline must succeed” at that point).

Case 1: running out of compute minutes in a month

Problem: Each push creates both a branch pipeline and an MR pipeline, and documentation changes also run the full test suite. Approach: Use the official workflow rules to remove duplicates; add rules:changes to heavy jobs; all test jobs interruptible: true and set auto_cancel. Result: compute-minute usage drops by about half (example). Limitations:changes always evaluates to true on the first push of a new branch, so it must be combined with compare_to: refs/heads/main.

Case 2: two green MRs turn main red after they are merged

Problem: MR A changed a function signature, and MR B added new code that calls the old signature; each MR pipeline passed on its own. Approach: Premium teams enable merged result pipelines, and merge trains for frequent merges; Free teams require “Fast-forward merge”, which forces the branch to be rebased onto the latest main and the pipeline to run again. Limitations: Fast-forward merge adds work for developers; merge trains lengthen merge wait times.

Case 3: an MR from a fork

Problem: An open-source project receives an MR from a fork, and by default the pipeline runs in the fork project, using the fork's Runners and variables, so the parent project's secrets are not visible. Approach: After the parent project's maintainers review the code, they can choose to run the pipeline in the parent project. Risk: Running in the parent project means the fork author's code can read the parent project's CI variables. Always review .gitlab-ci.yml and script changes first.

Common errors and fixes

Pipeline filtered out by workflow rules.

Cause: when a pipeline is created by a manual run or the API, no workflow rule matches its source (for example, web,api).

Fix: add rules such as - if: $CI_PIPELINE_SOURCE == "web" , and so on.

The resulting pipeline would have been empty. Review the rules configuration for the relevant jobs.

Cause: workflow allows creation, but no job's rules match (a common case: a job only has MR rules but runs on a branch).

glab ci lint --dry-run --ref main --include-jobs

Fix: complete the job rules, or leave out rules on always-on jobs (such as lint).

MR shows “detached pipeline detected” / two pipelines appear per push

Cause: job rules match both push and MR events, and there is no workflow de-duplication.

Fix: use the official workflow rules from this module.

jobs:deploy rules:changes always runs in scheduled pipelines

Cause: with no push event, changes is always true.

Fix: add - if: $CI_PIPELINE_SOURCE == "schedule" + when: never in front, or use compare_to.

The MR keeps showing “waiting for pipeline to finish”, but there is no MR pipeline in the pipeline list

Cause:“pipeline must succeed” is enabled, but the configuration has no rules for merge_request_event rules, so the MR never gets a pipeline; or merged results are enabled without MR pipelines configured (the docs explicitly warn that this leaves the MR stuck).

Fix: add MR rules, or temporarily turn off the merged results setting.

Command-line questions
1. Write rules that skip draft MRs, run other MRs, and run on main.
rules:
  - if: $CI_MERGE_REQUEST_DRAFT == "true"
    when: never
  - if: $CI_PIPELINE_SOURCE == "merge_request_event"
  - if: $CI_COMMIT_BRANCH == $CI_DEFAULT_BRANCH
2. List the 3 most recent MR pipelines.
glab ci list --source merge_request_event --per-page 3
Scenario analysis
The job rule is [- if: $CI_COMMIT_BRANCH == "main", - when: never], and a colleague says “I want it to run in MRs too”, so at the end of they added - if: $CI_PIPELINE_SOURCE == "merge_request_event", but it still does not run in MRs. Why?

Rules are checked in order, and the first match takes effect. The second - when: never has no conditions, so it matches every pipeline, and the rules after it are never checked. Move the MR rule ahead of when: never , or delete the unconditional never (a job that matches nothing is not added anyway).

Verified teaching videos

No dedicated walkthrough found rules / workflow:rules or video verified via oEmbed. For now, refer to the relevant chapters of the comprehensive course below, and treat this lesson and the official docs as authoritative:

▶
DevOps with GitLab CI Course - Build Pipelines and Deploy to AWS — freeCodeCamp.org
English · covers MR pipelines and controlling jobs by branch (recorded earlier; some parts use the legacy only/except syntax)

Official docs

Video storyboard script (about 90 seconds)

Shot 1 · 0–20s
Visual: a single push spawns two pipelines, and the billing meter spins fast.
Narration: when a job's rules allow both push and MR, one push runs it twice.
Shot 2 · 20–45s
Visual: the workflow gate. Three rules light up from top to bottom, and the second rule, “never if an MR is open”, blocks the branch pipeline.
Narration: the officially recommended workflow rules keep only the MR pipeline.
Shot 3 · 45–70s
Visual: job cards check the rules one by one; after the first match, the later rules turn grey.
Narration: the first match wins, and no match means the job is not added. Exclusion rules always go first.
Shot 4 · 70–90s
Visual: the source branch and main merge into one dashed commit, and the pipeline runs on top of it.
Narration: a merged result pipeline tests the code as it will be after the merge, and it requires Premium.
or score ≥ 70% in the quiz

Module 4 · variables, protected variables and CI/CD settings

21:00 – 28:00 · variables are merged from ten layers of sources. Protected decides “who can get them”; Masked only decides “whether they are visible in the log”
7 minFreeEnvironment scope for group variables: Premium★★★★★
Learning goals
  • Use predefined variables (CI_COMMIT_SHORT_SHA,CI_REGISTRY_IMAGE,CI_DEFAULT_BRANCH , etc.), define variables in YAML and in the UI, and state the precedence order.
  • Correctly configure Protected,Masked,Masked and hidden, and File types and environment scope, and understand each one's security boundary.
  • Know the default restriction on pipeline variables (new projects in new GitLab.com namespaces do not allow them by default), and the better places to keep secrets (external secret management, OIDC; Lessons 3/4).
Prerequisites: protected branches from Lesson 1; pipeline sources from Module 3. Importance:★★★★★ (secret leaks are the number one CI security risk)

What: where variables come from

SourceWhere it is definedExample
Predefined variablesInjected automatically by GitLabCI_PIPELINE_SOURCE,CI_COMMIT_SHORT_SHA (first 8 characters),CI_COMMIT_REF_PROTECTED,CI_REGISTRY_IMAGE,CI_JOB_TOKEN,CI_SERVER_FQDN
YAML variables.gitlab-ci.yml top level / job / rules:variables / workflow:rules:variablesPIP_DISABLE_PIP_VERSION_CHECK: "1"
project / group / instance variablesSettings → CI/CD → Variables (projects need Maintainer, groups need Owner, instances need an administrator)REGISTRY_PASSWORD
Pipeline variablesPassed in by manual runs, the API, trigger tokens, and scheduled runsglab ci run --variables KEY:VALUE
dotenv reportupstream job artifacts:reports:dotenv producesIMAGE_DIGEST=sha256:…

How: precedence (highest to lowest, official order)

  1. Variables in pipeline execution policies / scan execution policies
  2. Manual job variables (filled in when a manual job is run)
  3. Pipeline variables (manual runs, API, triggers, scheduled runs)
  4. Project variables
  5. Group variables (closer subgroups take precedence)
  6. Instance variables
  7. Variables from dependencies / needs job's dotenv report variables
  8. YAML variables: rules:variables > job variables > workflow:rules:variables > top level variables
  9. Deployment variables
  10. Predefined variables (of which CI_ENVIRONMENT_ID,CI_ENVIRONMENT_SLUG,CI_ENVIRONMENT_URL, and CI_PAGES_URL cannot be overridden)

Mnemonic: “The closer to this run and to manual action, the higher the precedence; YAML written in the repository ranks quite low.” So a project variable in the UI overrides a same-named variable in YAML. When troubleshooting “why my YAML change has no effect”, check the UI variables first.

Protection options: what each one guards against

OptionEffectDoes not protect against
Protect variableInjected only into pipelines running on protected branches / protected tagsanyone who can push to protected branches. MR pipelines can also access them when the conditions are met (source and target branches are both protected, same project, and the triggerer can push to the target branch) and “Allow MR pipelines to access protected variables and Runners” is turned on (from 18.1)
Masked (default from 18.3)Replaces the full value appearing in the job log with [MASKED]; requires a single line, no spaces, at least 8 characters, and the value cannot equal an existing variable nameecho $X | base64, printing it character by character, or writing it to artifacts. Masking is only string replacement in the log
Masked and hidden (project / group: GA in 17.6; instance: 19.0)On top of Masked, the value can never be seen in the UI again after saving; this can only be chosen at creationSame as Masked; the job can still read it
File typeThe value is written to a temporary file; the environment variable holds the file pathScripts read the cat file; but env/printenv does not print the contents directly.
Expand variable referenceReferences in the value such as $OTHER will be expanded.Masked variables cannot use this, and passwords whose values contain $ should have expansion turned off.
Environment scopeInjected only into deployment jobs for a specified environment (such as production)Project level is available at all layers; group level requires Premium

Why: why “protected + masked” is not enough

Anyone who can change pipeline configuration and run pipelines on a protected ref can read every injected variable. The official docs explicitly state that masking “is not a reliable way to stop malicious users from obtaining variable values”. So: ① tighten who can push or merge to protected branches (Lesson 1); ② during review, watch for changes to .gitlab-ci.yml and scripts; ③ replace long-lived credentials with short-lived ones. Lessons 3 and 4 use id_tokens OIDC federated identity to remove cloud keys entirely; ④ when you need real secret management, use an external secrets provider (Vault, Azure Key Vault, etc.) or GitLab Secrets Manager (GA in 19.5; Premium / Ultimate, requires an add-on).

When: pipeline variables

On GitLab.com,new projects in new namespaces, the “minimum role to use pipeline variables” defaults to no_one_allowed: glab ci run --variables … a pipeline that uses them will report Insufficient permissions to set pipeline variables. When it is really needed, an Owner adjusts this in Settings → CI/CD → Variables to maintainer or developer. Restricting pipeline variables is a deliberate security design: they have high precedence and can override project variables.

Comparison with similar technologies

GitLabGitHub ActionsAzure PipelinesJenkins
Secret storageCI/CD variables (Masked / Protected)Secrets (automatically masked)Secure variables / variable groups + Key VaultCredentials plugin
Restrict by branchProtect variableEnvironments + protection rulesEnvironment approval / branch control checksFolder / credential scope
Short-lived cloud credentialsid_tokens (Lessons 3/4)permissions: id-token: writeWorkload identity federation service connectionPlugin implementation
Common misconceptions① “Masked variables are safe”: masking is just log replacement. ② “Protected variables also work in MRs”: by default MR pipelines do not run on protected refs, so they cannot get them; this requires the conditions to be met and an explicit opt-in. ③ “Variables in YAML take precedence over the UI”: the opposite is true. ④ “The value of a File-type variable is its content”: it is a file path, so you should use kubectl --kubeconfig "$KUBECONFIG_FILE" to read it.

Variable merging: ten layers of sources; higher layers override lower ones

1 Policy variables (security / pipeline execution policies) 2 Manual job variables 3 Pipeline variables (web / api / trigger / schedule) 4 Project variables (Settings → CI/CD → Variables) 5 Group variables (nearest subgroup first) 6 Instance variables 7 dotenv report variables (needs / dependencies) 8 YAML: rules:variables > job > workflow > top level 9 Deployment variables 10 Predefined variables Precedence increases Filtering before injection Protected? → injected only if the ref is protected Environment scope? → matches the job's environment File type? → write a temporary file; the variable = the path Expand? → expand $OTHER references When the job runs The Runner does string replacement on the log: Masked value → [MASKED] (does not affect reads inside the job)
Figure 4-1: filter first (protected / scope), then merge by precedence, and finally mask at the log level

Interactive parser: what is the final DEPLOY_ENV, and what could leak into the log?

On the left, tick the layers where DEPLOY_ENV is defined and choose the branch to run. On the right, enter a secret value to see how masking applies and which ways of writing it bypass masking.

Core commands

CommandPurposeKey arguments
glab variable set KEY -v VALUECreate / update a project variable-m masked,-p protected,--hidden,-t file,-s production,-r raw (no expansion),-g group
glab variable listList variables (hidden variables do not show their values)-g
glab variable get KEYRead a valueRequires Maintainer
glab variable delete KEYDelete-s Specify the scope
glab ci run --variables K:VRun with pipeline variablesRestricted by the “minimum role” setting
cd ~/gitlablab/myapp
# Protected + masked + raw (a $ in the value is not expanded)
glab variable set DEMO_TOKEN -v 'glpat-EXAMPLE' -p -m -r
# File type: the value is written to a temporary file
glab variable set APP_CONFIG -t file -v $'LOG_LEVEL=info\nFEATURE_X=on'
glab variable list
✓ Created variable DEMO_TOKEN for mygroup-lab/myapp with scope *.
✓ Created variable APP_CONFIG for mygroup-lab/myapp with scope *.
KEY          PROTECTED  MASKED  EXPANDED  SCOPE  DESCRIPTION
APP_CONFIG   false      false   true      *
DEMO_TOKEN   true       true    false     *

Verify: In the job, echo "$APP_CONFIG" prints a path for a /builds/mygroup-lab/myapp.tmp/APP_CONFIG type variable. Common errors: Saving fails when the value does not meet the masking requirements (fewer than 8 characters, or containing spaces or newlines). For multi-line certificates, use File type instead of Masked.

Common predefined variables

VariableExample valuePurpose
CI_COMMIT_SHORT_SHA8f3c2a1bImage tag
CI_COMMIT_REF_SLUGfeature-loginURL / branch name safe for image tags
CI_REGISTRY_IMAGEregistry.gitlab.com/mygroup-lab/myappPush an image (only available when the Container Registry is enabled)
CI_REGISTRY_USER / CI_REGISTRY_PASSWORDJob-specific credentialdocker login $CI_REGISTRY
CI_JOB_TOKENValid while the job runsCall some APIs, pull permitted private projects / packages
CI_COMMIT_REF_PROTECTEDtrueDetermine whether the ref is protected

Lab 4: verify protected variables and masking (about 6 minutes)

Create variables ( glab variable set the two commands on the previous page). Confirm that main is a protected branch (set in Lesson 1):
glab api "projects/:id/protected_branches" | python3 -c 'import sys,json;print([b["name"] for b in json.load(sys.stdin)])'
['main']
Write a check job (for this lab only; delete it when done):
vars-demo:
  stage: lint
  needs: []
  image: alpine:3.22
  rules:
    - if: $CI_PIPELINE_SOURCE == "merge_request_event"
    - if: $CI_COMMIT_BRANCH
    - if: $CI_COMMIT_TAG
  variables:
    DEPLOY_ENV: from-yaml
  script:
    - echo "ref=$CI_COMMIT_REF_NAME protected=$CI_COMMIT_REF_PROTECTED source=$CI_PIPELINE_SOURCE"
    - echo "DEPLOY_ENV=$DEPLOY_ENV"
    - '[ -n "$DEMO_TOKEN" ] && echo "DEMO_TOKEN present: $DEMO_TOKEN" || echo "DEMO_TOKEN absent"'
    - echo "APP_CONFIG is a path -> $APP_CONFIG"; cat "$APP_CONFIG"
git commit -am "ci: vars demo" && git push          # still on feat/ci-pipeline
glab ci status --wait
glab ci trace vars-demo -b feat/ci-pipeline
ref=feat/ci-pipeline protected=false source=merge_request_event
DEPLOY_ENV=from-yaml
DEMO_TOKEN absent
APP_CONFIG is a path -> /builds/mygroup-lab/myapp.tmp/APP_CONFIG
LOG_LEVEL=info
FEATURE_X=on
Run on a protected ref: main forbids direct pushes, and Lesson 1 set all tags as protected (Maintainers only). Pushing a temporary tag produces a protected tag pipeline (the workflow rules already include $CI_COMMIT_TAG):
git tag vars-test && git push origin vars-test
glab ci status -b vars-test --wait
glab ci trace vars-demo -b vars-test
ref=vars-test protected=true source=push
DEPLOY_ENV=from-yaml
DEMO_TOKEN present: [MASKED]
Experience precedence: glab variable set DEPLOY_ENV -v from-project-ui, push once more (MR pipeline), and the output becomes DEPLOY_ENV=from-project-ui— project variables override the YAML. When the lab ends, delete the temporary tag and the variable:
git push origin --delete vars-test && git tag -d vars-test
glab variable delete DEPLOY_ENV
glab variable delete DEMO_TOKEN
glab variable delete APP_CONFIG
# remove the vars-demo job from .gitlab-ci.yml and commit

Case 1: production credentials leak into feature branch logs

Problem: The cloud key used for deployment was set as Masked only, not Protected. While debugging on a feature branch, the developer echo $KEY | base64, and the key appeared in the log. Approach: Rotate the key immediately; change all deployment credentials to Protected; then move to OIDC (Lessons 3/4) so the pipeline no longer holds long-lived keys. Limitations: Protected variables depend on protected-branch settings. Whoever can push to main can read them.

Case 2: a kubeconfig in a regular variable causes a “file name too long” error

Problem: The kubeconfig content was put in a regular variable, and the script kubectl --kubeconfig $KUBECONFIG fails. Approach: Change it to a File-type variable, whose value is the file path. A better approach is the GitLab agent for Kubernetes (Lesson 5), which needs no kubeconfig secret.

Case 3: a scheduled run overrode the production configuration

Problem: In a scheduled run, someone set the DEPLOY_ENV=staging pipeline variable, which overrode the project variable, and the overnight job deployed the staging configuration to production. Approach: Set the “minimum role to use pipeline variables” to maintainer or no_one_allowed; deployment jobs use environment + environment-scoped variables; print and validate key variables at the start of the job.

Common errors and fixes

Saving a Masked variable fails (symptom: the UI / API says the value does not meet masking requirements, e.g. fewer than 8 characters, or containing spaces or newlines)

Cause: the value does not meet the masking requirements (single line, no spaces, at least 8 characters; when expansion is on, only some symbols are allowed).

Fix: use File type for multi-line or space-containing values; or store it base64-encoded and decode it in the job (write the decoded result to a file, and do not echo it).

Insufficient permissions to set pipeline variables

Cause: the project's “minimum role to use pipeline variables” is higher than your role (new projects in new GitLab.com namespaces default to no_one_allowed).

Fix: use project variables instead, or ask an Owner to adjust the setting.

Variable has a value on main but is empty in MR pipelines

Cause: the variable is Protected, and MR pipelines do not run on protected refs.

echo "$CI_COMMIT_REF_PROTECTED $CI_PIPELINE_SOURCE"

Fix: This is correct behavior when the MR stage does not need production credentials. If access is really needed, meet the official conditions and turn on “Allow MR pipelines to access protected variables and Runners”.

The $ characters in a password disappear or get replaced

Cause: When “Expand variable reference” is on, $abc is treated as a variable reference and expanded.

Fix: turn off expansion (with glab, use -r); in YAML you can write $$ escapes, or use variables:expand: false.

Changed the variable value in .gitlab-ci.yml but it has no effect

Cause: a same-named project / group / pipeline variable has higher precedence.

glab variable list
glab variable list -g mygroup-lab

Fix: delete or rename one of them, so there is a single source.

Command-line questions
1. Create a protected, masked, raw (non-expanded) variable NPM_TOKEN for the mygroup-lab group.
glab variable set NPM_TOKEN -v "$NPM_TOKEN_VALUE" -g mygroup-lab -p -m -r
2. Save a TLS certificate as a File-type variable.
glab variable set TLS_CA -t file -v "$(cat ca.pem)"
Scenario analysis
Security audit finding: any Developer can read the production database password from their own feature branch. The variable is already Masked; where is the problem, and how should it be fixed in layers?

Masked only masks the log; it does not restrict injection. The variable is not Protected, so pipelines on every branch can get it. Fix: ① rotate the password immediately; ② set it to Protected, and confirm that only Maintainers can push / merge to protected branches; ③ deployment jobs use environment: production + environment-scoped variables; ④ move long-term to external secret management or short-lived OIDC credentials; ⑤ during MR review, watch for changes to the CI configuration.

Verified teaching videos

▶
Managing the Complex Configuration Data Management Monster Using GitLab — GitLab Unfiltered
English · a talk referenced by the official CI/CD variables docs, covering the variable hierarchy and configuration management
▶
GitLab CI CD Tutorial for Beginners [Crash Course] — TechWorld with Nana
English · demo with protected and masked variables (the interface is older; the default visibility changed to Masked in 18.3)

Official docs

Video storyboard script (about 90 seconds)

Shot 1 · 0–25s
Visual: ten layers of transparent film stacked together; the value on the top layer covers the layers below.
Narration: variables come from ten layers of sources. The closer to this run, the higher the precedence; values written in YAML actually rank lower.
Shot 2 · 25–50s
Visual: a lock hangs on the main branch; the key is only issued to pipelines on main, and pipelines on feature branches come up empty-handed.
Narration: protected variables are only injected into pipelines on protected branches and tags.
Shot 3 · 50–75s
Visual: in the log the secret becomes [MASKED], but a base64 string beside it is still exposed.
Narration: masking is only string replacement in the log. It is not access control.
Shot 4 · 75–90s
Visual: the long-lived key is replaced by a token with a countdown.
Narration: the best secret is no secret. Lessons 3 and 4 use OIDC to exchange for short-lived credentials.
or score ≥ 70% in the quiz

Module 5 · Runners: GitLab-hosted, self-managed and executors

28:00 – 35:00 · which machine a job runs on depends on scope, tags, protection settings and who claims it first. Registering a new Runner uses the glrt- authentication token
7 minGitLab Runner 19.5.3Old registration tokens: deprecated, planned for removal in 20.0★★★★★
Learning goals
  • Describe the machine types, tags, default image and compute-minute rules of GitLab-hosted Runners.
  • Use the new registration flow (first create a Runner in GitLab to get an glrt- authentication token, then run gitlab-runner register --token) to run a container in Docker gitlab-runner, with tags lab-docker, configured in ~/gitlablab/runner.
  • Understand the job-to-Runner matching rules (scope, tags, Run untagged, Protected, Paused), and choose an executor for each scenario.
Prerequisites: containers and volumes from the Docker course; the polling mechanism from Module 1. Importance:★★★★★

What: GitLab-hosted Runners (GitLab.com)

Linux x86-64 machine typesTagsvCPU / memory / storageTier
Small (default)saas-linux-small-amd642 / 8 GB / 30 GBAll
Mediumsaas-linux-medium-amd644 / 16 GB / 50 GBAll
Large / XLarge / 2XLargesaas-linux-large-amd64 etc.8–32 vCPUPremium / Ultimate
Arm64 Smallsaas-linux-small-arm642 / 8 GB / 30 GBAll (Medium and above require Premium)
  • Untagged jobs run on Small Linux x86-64; If image is not written, the default is ruby:3.1— so every job should explicitly specify its image.
  • Each job uses a fresh temporary VM, destroyed when the job ends; Docker-in-Docker is available.
  • Compute minutes: the Free tier gets 400 minutes per top-level namespace per month, and paid tiers get more. Consumption = job duration × machine cost factor (Small is 1; larger machines have higher factors). When the quota is used up, hosted Runners stop running jobs for that namespace; self-managed Runners are not affected.
  • Identity verification: GitLab.com requires email, phone or credit card verification for accounts based on risk (cards are not charged or stored). If you see verification-related errors when running pipelines, complete verification first. The exact rules change, so refer to the Identity verification documentation for the current rules.
  • Windows, macOS and GPU machine types are also available; for the available tiers and status, follow the official docs.

What: scope and settings of self-managed Runners

ScopeWho can create itWho can use it
Instance RunnerSelf-managed instance administrators (on GitLab.com, this is the hosted Runner)All projects in the instance (projects can opt out)
Group RunnerGroup OwnerAll projects in the group and its subgroups
Project RunnerProject MaintainerSpecified projects (can be reassigned to other projects unless locked)

Key settings for each Runner: Tags (the job's tags must all be included in the Runner's tags),Run untagged jobs Run untagged (whether it accepts untagged jobs),Protected Protected (accepts only jobs on protected branches / tags),Paused Paused,Maximum job timeout. For Runners created with the new flow, manage these in the GitLab UI / API. Using --token glrt-… if you still pass --tag-list,--run-untagged,--locked,--access-level,--maximum-timeout,--paused,--maintenance-note,register during registration will cause an immediate error and exit.

How: the new registration flow (runner authentication token)

  1. In GitLab,create a Runner: Settings → CI/CD → Runners → “New project runner” (requires Maintainer), enter tags and a description → get an authentication token starting with glrt- (shown only once). The API can also create one POST /user/runners (the token needs the create_runner scope).
  2. On the Runner host, run gitlab-runner register --url https://gitlab.com --token glrt-… --executor docker …, and the token is written to config.toml.
  3. The Runner starts polling, and GitLab shows this Runner as online.

The old flow (project / group “registration token” + --registration-token) is deprecated, and the docs say it is planned for removal in GitLab 20.0. Passing a glrt- token to the old parameter --registration-token puts registration into “compatibility mode” (introduced in 16.2); these parameters only print a warning and are ignored.

Executor overview

ExecutorStatus (official)IsolationSuited to
DockerActiveOne container per jobThe default choice; supports image/services
Docker AutoscalerActiveCreates cloud VMs on demand, then runs containers on themElastic scaling (replaces Docker Machine)
InstanceActiveOne on-demand VM per job, exclusiveJobs that need a full VM
KubernetesActiveOne Pod per jobExisting K8s platform (Lesson 7)
ShellMaintenance modeNo isolation; runs directly on the hostSpecial hardware, minimal scenarios
SSH / VirtualBox / Parallels / CustomMaintenance modeDepends on implementationLegacy or custom environments
Docker MachineDeprecated—Migrate to Docker Autoscaler

Why / When: when a self-managed Runner is needed

  • Needs access to internal resources, private image registries, or special hardware (GPU, ARM, large memory).
  • Compute minutes are not enough, or there are very many jobs and self-hosting is cheaper.
  • Compliance requires that code and build outputs stay within your own infrastructure.

Security model

A Runner executes the code in the repository. Anyone who can modify .gitlab-ci.yml can run arbitrary commands on the Runner. Therefore: production deployment Runners are set to Protected; do not share Runners that mount the Docker socket or run in privileged mode with untrusted projects (both are equivalent to host root); the Runner host does not store long-lived cloud credentials; upgrade Runners regularly (keep them in step with the GitLab major version).

Comparison with similar technologies

GitLab RunnerGitHub Actions RunnerAzure Pipelines AgentJenkins Agent
HostedGitLab-hosted RunnerGitHub-hosted runnersMicrosoft-hosted agentsNo official hosted option
Registration credentialglrt- Authentication tokenRegistration token (short-lived)PAT / agent poolNode secret (JNLP)
How to choosetagsruns-on Tagspool + demandsagent { label }
Common misconceptions① “The job has written tags: [docker], so any Runner with a docker tag will take it”: it must also meet scope, protection and other conditions. ② “Runner tags are set with --tag-list during register”: in the new flow this fails; tags are set in the UI / API. ③ “More Runners means faster”: concurrent (global concurrency) defaults to 1 in the generated configuration. If you register without tuning it, only one job runs at a time.

Composition of a self-managed Runner (Docker executor)

Lab machine (Ubuntu 24.04 + Docker Engine 29) container gitlab-runnergitlab/gitlab-runner:v19.5.3polls gitlab.com · concurrenttags (UI): lab-docker ~/gitlablab/runner→ /etc/gitlab-runner/config.tomltoken = "glrt-…" (keep secret!) /var/run/docker.sockthe Runner uses it to create“sibling” containers⚠ equivalent to host root helper containergitlab-runner-helper: git clone, cache, artifacts build container (job image)runs before_script + script service containerredis:8 / docker:29-dind (privileged) Docker volume: runner-xxxx-cache-…(local cache, Module 6)
Figure 5-1: gitlab-runner itself is only a scheduler; jobs run in sibling containers that it creates through the Docker socket

Matching conditions for jobs and Runners

pending job Runner is onlineand not paused available to this project(instance / group / project) job tags ⊆ Runner tagsuntagged → needs Run untagged Runner is protected?→ the ref must be protected The first requester gets it
Figure 5-2: among the Runners that meet all conditions, the one that first sends jobs/request claims the job

Interactive simulator: which Runner claims these jobs?

Adjust the Runner and project settings, then click “Simulate one polling round”. Each Runner sends its request after a random delay POST /api/v4/jobs/request, and GitLab only hands it jobs that meet all conditions.

Core commands

CommandPurposeNotes
gitlab-runner register --non-interactive --url … --token glrt-… --executor docker --docker-image …Register with an authentication tokentags and other settings are set in the UI
gitlab-runner verifyCheck whether the token is valid--delete Delete invalid entries
gitlab-runner listList the Runners in config.toml
gitlab-runner unregister --name …Unregistercan also be deleted in the UI
gitlab-runner runRun in the foreground (the container's default command)Reloads automatically after config.toml is changed
glab api --method POST user/runners -f …Create a Runner via the API; returns a glrt- tokenThe access token needs the create_runner scope
concurrent = 1
check_interval = 0          # 0 means use the default of 3 seconds

[[runners]]
  name = "lab-docker-runner"
  url = "https://gitlab.com"
  id = 51234567
  token = "glrt-xxxxxxxxxxxxxxxxxxxx"   # authentication token; equivalent to a password
  executor = "docker"
  [runners.docker]
    image = "alpine:3.22"
    privileged = true
    volumes = ["/certs/client", "/cache"]
    pull_policy = ["if-not-present"]

Notes:concurrent is the upper limit on the number of jobs the whole process runs at the same time; [[runners]] limit limits a single Runner entry (default 0 = unlimited); request_concurrency defaults to 1. pull_policy The default is always, and changing it to if-not-present reduces pulls but may use stale images. privileged = true needed for Docker-in-Docker; for the security cost, see “Principles”.

Lab 5: run a self-managed Runner in Docker (about 8 minutes)

Cost and risk: Use the lab machine from the Docker course; no extra cost. The Runner mounts the Docker socket and runs in privileged mode, so use it only for lab projects. Permissions required: Project Maintainer (to create in the UI) or Owner (to create via the API).

Start the Runner container (the official Docker installation method, with the config directory set to the course convention ~/gitlablab/runner):
mkdir -p ~/gitlablab/runner
docker run -d --name gitlab-runner --restart always \
  -v "$HOME/gitlablab/runner:/etc/gitlab-runner" \
  -v /var/run/docker.sock:/var/run/docker.sock \
  gitlab/gitlab-runner:v19.5.3
docker exec gitlab-runner gitlab-runner --version | head -2
Version:      19.5.3
Git revision: …
Create a Runner in GitLab to get a glrt- token. Method A (UI): Settings → CI/CD → Runners → New project runner → enter the tag lab-docker,do not tick Run untagged → enter the description lab-docker-runner → create → copy the glrt-… from the page. Method B (API):
PID=$(glab api projects/:id | python3 -c 'import sys,json;print(json.load(sys.stdin)["id"])')
glab api --method POST user/runners \
  -f runner_type=project_type -f project_id=$PID \
  -f tag_list=lab-docker -f run_untagged=false -f description=lab-docker-runner
{"id":51234567,"token":"glrt-xxxxxxxxxxxxxxxxxxxx","token_expires_at":null}

The API method requires the access token used by glab to include the create_runner scope; if you get a 403, use method A. The token is returned only once.

Register (do not write the token into shell history: use read -s):
read -rs RUNNER_TOKEN   # paste glrt-… then press Enter
docker exec gitlab-runner gitlab-runner register --non-interactive \
  --url "https://gitlab.com" \
  --token "$RUNNER_TOKEN" \
  --executor "docker" \
  --docker-image "alpine:3.22" \
  --docker-privileged \
  --docker-volumes "/certs/client" \
  --description "lab-docker-runner"
unset RUNNER_TOKEN
docker exec gitlab-runner gitlab-runner verify
sudo grep -E "concurrent|name|executor|privileged" ~/gitlablab/runner/config.toml
Runtime platform  arch=amd64 os=linux …
Verifying runner... is valid  runner=xxxxxxxx
concurrent = 1
  name = "lab-docker-runner"
  executor = "docker"
    privileged = true
Raise concurrency to 2 (the Runner reloads its configuration automatically):
sudo sed -i 's/^concurrent = .*/concurrent = 2/' ~/gitlablab/runner/config.toml
docker logs --tail 5 gitlab-runner
Configuration loaded  builds=0 max_builds=2
Make a job run on the self-managed Runner: in integration-test and build-image add tags: [lab-docker], and after pushing, check the first line of the log:
git commit -am "ci: use self-managed runner" && git push
glab ci trace integration-test | head -3
docker ps --format '{{.Names}}  {{.Image}}' | grep runner-
Running with gitlab-runner 19.5.3 (…)
  on lab-docker-runner glrt-xxxx, system ID: s_…
Preparing the "docker" executor
runner-abcd1234-project-61234567-concurrent-0-…-build      python:3.13-slim
runner-abcd1234-project-61234567-concurrent-0-…-predefined registry.gitlab.com/gitlab-org/gitlab-runner/gitlab-runner-helper:…

The job log shows the Runner name and token prefix, but never shows the full token. These jobs consume no compute minutes.

Cleanup (after the course): keep the Runner for use in later courses. To remove it, delete the Runner in the UI (its token becomes invalid), then docker rm -f gitlab-runner && sudo rm -rf ~/gitlablab/runner.

Case 1: migrating from registration tokens to authentication tokens

Problem: An automation script registered Runners in bulk with project registration tokens. GitLab warns that registration tokens are deprecated and planned for removal in 20.0. Approach: Change it to first call POST /user/runners (or Terraform's gitlab_user_runner resource) to create a Runner and get an glrt- authentication token, then register --token; move the tags, protection and similar attributes into the API parameters. Limitation: the access token used to create Runners needs the create_runner scope; use a dedicated service account and rotate it regularly.

Case 2: a shared Runner used for lateral movement

Problem: A group Runner had privileged mode enabled and was open to all projects; a pipeline in an intern's project left a backdoor on the host. Approach: Switch the production-related Runners to Protected and assign them only to specific projects; remove privileged mode from general-purpose Runners; switch image builds to daemonless tools (such as BuildKit rootless or Kaniko-style tools, chosen per the official docs); make Runner hosts ephemeral (Docker Autoscaler / Kubernetes).

Case 3: hosted Runner minutes are not enough, so use a mix

Approach: Keep lint and unit tests on hosted Runners (no maintenance, high parallelism); move integration tests and image builds to a self-managed Runner (tag tags: [lab-docker]). Note: If a project disables instance Runners, untagged jobs get stuck because there is no Runner with Run untagged.

Common errors and fixes

ERROR: Verifying runner... is not valid / 403 Forbidden

Cause: wrong token, the Runner was deleted in the UI, or an old registration token was used as an authentication token.

docker exec gitlab-runner gitlab-runner verify --delete

Fix: recreate the Runner in the UI and register with the new glrt- token.

FATAL: Runner configuration other than name and executor configuration is reserved (specifically --locked, --access-level, --run-untagged, --maximum-timeout, --paused, --tag-list, and --maintenance-note) and cannot be specified when registering with a runner authentication token.

Cause: the command was run using --token glrt-… with parameters passed at registration that the server manages (common when copying flags from old tutorials, such as --tag-list).

Fix: remove these parameters and run register again. Set tags, Run untagged, protection and the like on the Runner's edit page in the UI, or via the API.

Cannot connect to the Docker daemon at tcp://docker:2376. Is the docker daemon running?

Cause: The dind service requires privileged mode and a shared TLS certificate directory.

Fix: In config.toml, set privileged = true and volumes = ["/certs/client", …]; in the job, set DOCKER_TLS_CERTDIR: "/certs".

Job stays pending: This job is stuck because the project doesn't have any runners online assigned to it.

Cause: the project disabled instance Runners, and the project / group Runners are offline or do not accept this job.

docker ps --filter name=gitlab-runner
docker logs --tail 20 gitlab-runner

Fix: start the Runner; check the tags, Run untagged and Protected settings (step through them with this module's simulator).

No space left on device (on the Runner host)

Cause: job images, cache volumes and build layers have piled up.

docker system df
docker volume ls --filter name=runner- | wc -l

Fix: clean up regularly (docker system prune — be careful, it deletes cache volumes). In production, use an ephemeral host or the official clear-docker-cache script (Lesson 7).

Command-line questions
1. List this project's project Runners and their online status.
glab api "projects/:id/runners?type=project_type" | python3 -c 'import sys,json;[print(r["id"],r["description"],r["status"],r["paused"]) for r in json.load(sys.stdin)]'
2. Delete the invalid Runner entries from config.toml.
docker exec gitlab-runner gitlab-runner verify --delete
Scenario analysis
The team added tags: [prod-deployer] to the deploy job and set the prod-deployer Runner to Protected. A developer pushed a modified deploy job on a feature branch; it stays pending, and the developer thinks the Runner is broken. What actually happened, and is it good or bad?

A protected Runner only accepts jobs from protected branches / tags, so the feature branch's job is never claimed and stays pending (the page says no usable Runner is available). This is intended: it stops unmerged code from running on a Runner that has production access. Deploy only after the change is merged into a protected branch, and use rules so deploy only appears on main to avoid confusion.

Verified teaching videos

▶
GitLab CI CD automation (Docker, Kubernetes, Terraform, and more…) — Christian Lempa
English · demo with a self-managed Runner and the Docker executor. Recorded earlier, so for registration steps follow this lesson's glrt- flow
▶
GitLab CI CD Tutorial for Beginners [Crash Course] — TechWorld with Nana
English · Runner and executor concepts (the registration token flow is deprecated)

Official docs

Video storyboard script (about 90 seconds)

Shot 1 · 0–20s
Visual: in the GitLab UI, click “New project runner”, and a token starting with glrt- pops up.
Narration: the new flow creates the Runner in GitLab first, and you get an authentication token starting with glrt.
Shot 2 · 20–45s
Visual: in the terminal, docker run and register run; the token appears in config.toml, and the Runner turns green in the UI.
Narration: register on the host with this token; tags and other settings are managed in GitLab.
Shot 3 · 45–70s
Visual: three Runners raise their hands to grab a job; only the one whose tags and protection settings both match gets the card.
Narration: the job's tags must all be included in the Runner's tags, and a protected Runner accepts only protected branches.
Shot 4 · 70–90s
Visual: a red warning lights up on the Docker socket icon.
Narration: anyone who can change the pipeline can run commands on the Runner, so privileged Runners must be isolated.
or score ≥ 70% in the quiz

Module 6 · cache, artifacts and dependency passing

35:00 – 42:00 · cache is “best-effort acceleration”, and artifacts are “reliable result passing”. Use the wrong one and the pipeline is either slow or fails at random
7 minFree★★★★☆
Learning goals
  • Explain how cache and artifacts differ in storage location, lifecycle, reliability and purpose.
  • Design pip dependency caching with cache:key:files,fallback_keys, and policy ; understand cache isolation for protected branches.
  • Pass results between jobs using artifacts (paths,expire_in,when,reports:junit,reports:dotenv), and control downloads with needs / dependencies .
Prerequisites: the Module 1 execution steps (restore cache → download artifacts → script → save cache → upload artifacts); needs from Module 2. Importance:★★★★☆

What: the essential difference between the two

cacheartifacts
PurposeDependencies and other content that can be re-downloaded (pip, npm, Maven local repository)Build results, test reports, and files to be passed to later jobs or downloaded
Where it is storedStored by default on the Runner's machine (the Docker executor uses Docker volumes); with a distributed cache configured, on S3 / GCS / Azure. GitLab.com hosted Runners share a GCS distributed cache (automatically deleted if not updated for 14 days; a single compressed cache is at most 5 GB)Uploaded to GitLab (GitLab.com: a single compressed artifact is at most 1 GB)
ReliabilityNot guaranteed to exist: changing Runners, the cache being cleaned up, or a changed key all cause a missGuaranteed: later jobs can always download them (while not expired)
LifecycleReused across pipelines until overwritten or cleaned upExpires after 30 days by default (GitLab.com; can be changed with expire_in ); by default, keeps the artifacts of the latest successful pipeline for each ref
ScopeAll jobs / pipelines with the same key (protected and unprotected branches are separated by default)Later jobs in the same pipeline (and needs:pipeline:job etc.)
DefaultNo cache unless definedLater stages download all earlier stages' artifacts by default

How: key fields of cache

  • key: a string (variables can be used, such as $CI_COMMIT_REF_SLUG) or key:files (the SHA is computed from the contents of up to 2 files; since 19.5, a feature flag that is off by default can extend this to 10 files), and you can add key:prefix. If none of the files exist, the key falls back to default. There is also key:files_commits (computed from each file's latest commit; cannot be used together with files).
  • fallback_keys: backup keys tried in order when the primary key has no cache (such as the default branch's cache).
  • policy policy: pull-push (default),pull (read-only, suited to parallel test jobs),push (write-only).
  • when paths: on_success (default),on_failure,always. paths Must be a path inside the project directory.
  • A job can have at most 4 caches.
  • Protected branch isolation: pipelines run by a Maintainer / Owner on protected branches or tags automatically add a -protected suffix to the cache key; others use -non_protected— this stops a feature branch from poisoning the cache that main's release job uses. You can turn off “Use separate caches for protected branches” under Settings → CI/CD → General pipelines (not recommended).

How: key fields of artifacts

  • paths / exclude / untracked: the files to upload.
  • expire_in: for example 1 week,never; a number without a unit is treated as seconds.
  • when when: on_success (default),on_failure (saves debugging material only on failure),always (timed-out jobs do not upload).
  • reports Reports: junit (show test results in the MR),coverage_report (show coverage in the MR diff),dotenv (turns KEY=VALUE files into variables for later jobs), etc. Report artifacts are uploaded whether the job succeeds or fails.
  • expose_as: shows a download link on the MR page.
  • Download control: jobs that use needs only download the artifacts of the jobs they need. When needs is not used, dependencies: [job] can limit which ones are downloaded, and dependencies: [] downloads no artifacts at all.

When: put it in cache or artifacts?

ContentWhere to put itReason
pip / npm downloaded packagescacheIf lost, they can be re-downloaded; it is just slower
Build outputs dist/, wheelsartifactsLater deployment must get the same copy
Test reports report.xml, coverage.xmlartifacts:reportsDisplayed in the MR
.venv Virtual environmentsUse with caution: a cacheis tied to the Python version in the image and may break after the image is upgraded; caching the pip download directory is recommended.
Image build layersContainer Registry (BuildKit cache-to / cache-from)Not suited to the CI cache

Comparison with similar technologies

GitLabGitHub ActionsAzure PipelinesJenkins
Dependency cachecache (Runner-local or distributed)actions/cache (GitHub storage)Cache@2 TaskWorkspace retention / plugin
Result passingartifacts + needsupload/download-artifactPipeline Artifactsstash/unstash,archiveArtifacts
Test reportsreports:junitThird-party ActionPublishTestResultsjunit Steps
Common misconceptions① “Use cache to pass build results to deploy”: a different Runner means a miss, so you deploy old files or fail; you must use artifacts. ② “A cache hit is always faster”: when the cache is large, uploading and downloading it can be slower than reinstalling; use policy: pull read-only (pull) and clean it up regularly. ③ “Feature branch caches can also be used by main”: by default protected and unprotected caches are kept separate; this is a security design.

Flow of cache and artifacts within one job

Cache storageRunner local volumeor S3 / GCS (distributed)key: 1-3f9a…-non_protected GitLab artifact storageObject storageexpire_in defaults to 30 daysMR reports / downloads Job unit-test (Docker executor) 1 Restoring cache (hit / fallback key / miss) 2 Downloading artifacts (needs / dependencies) 3 script: pip install (fast on a hit) + pytest 4 Saving cache (policy: pull-push) 5 Uploading artifacts (report.xml) Job succeeded Next pipelineSame key → reuse the cache(may miss on another Runner) Later jobs in the same pipelineare guaranteed to get the artifacts(not expired + listed in needs)
Figure 6-1: the cache (orange) is best-effort across pipelines; artifacts (blue) are reliably passed within the same pipeline

Interactive simulation: cache hits and artifact passing across two consecutive pipelines

Choose what changes before the second run, then click “Run pipeline”. The simulator computes the cache key (the SHA of key:files + protected suffix), determines hit / fallback / miss, and shows pip install time and artifact passing.

Common configuration and commands

.python-job:
  variables:
    PIP_CACHE_DIR: "$CI_PROJECT_DIR/.cache/pip"   # cache paths must be inside the project directory
  cache:
    key:
      files: [requirements.txt, requirements-dev.txt]
      prefix: pip
    fallback_keys: [pip-default-protected]   # example: backup key used when the primary key is missing
    paths: [.cache/pip]
    policy: pull-push
ActionMethod
Clear Runner cacheBuild → Pipelines → More actions → “Clear Runner cache” (requires Developer; in practice it increments an internal index, and old caches are not deleted immediately)
Download the latest artifactsglab job artifact main "unit-test: [3.13]"
Browse / delete artifactsBuild → Artifacts; or “Browse / Download / Delete” on the right of the job page
Download via the APIglab api "projects/:id/jobs/artifacts/main/download?job=JOB_NAME" > a.zip
glab job artifact main "unit-test: [3.13]" --path ./artifacts
ls -R ./artifacts
Downloaded artifacts …
./artifacts:
report.xml  coverage.xml

The corresponding lines in the log:Checking cache for pip-3f9a…-non_protected...,Successfully extracted cache / WARNING: file does not exist (miss),Creating cache pip-3f9a…-non_protected...,Uploading artifacts for successful job.

Lab 6: pip cache + JUnit report + passing values with dotenv (about 7 minutes)

Add a coverage tool:
echo "pytest-cov>=6" >> requirements-dev.txt
Modify .python-job and unit-test:
.python-job:
  variables:
    PIP_CACHE_DIR: "$CI_PROJECT_DIR/.cache/pip"
  cache:
    key:
      files: [requirements.txt, requirements-dev.txt]
      prefix: pip
    paths: [.cache/pip]
  before_script:
    - pip install -q -r requirements-dev.txt

unit-test:
  stage: test
  extends: .python-job
  needs: [lint]
  parallel:
    matrix:
      - PY: ["3.12", "3.13"]
  image: python:${PY}-slim
  script:
    - pytest -q tests/test_app.py --junitxml=report.xml --cov=app --cov-report=term --cov-report=xml
  coverage: '/TOTAL.*? (\d+(?:\.\d+)?)%/'
  artifacts:
    when: always
    expire_in: 1 week
    reports:
      junit: report.xml
      coverage_report:
        coverage_format: cobertura
        path: coverage.xml

The two copies of the matrix use different Python versions, but the key depends only on the dependency file, so they share the same pip download cache. This is safe for pip (pip only selects wheels compatible with the current Python); the downside is that the two copies overwrite each other's cache writes. If you want each copy to be independent, add a predefined variable to the prefix, for example prefix: pip-$CI_JOB_NAME_SLUG (key:prefix supports strings and predefined variables; a cache key cannot contain /, so do not use the full image name directly).

Use dotenv to pass the image tag to later jobs:
build-image:
  # …keep the configuration from Modules 2 / 5…
  script:
    - docker build -t myapp:$CI_COMMIT_SHORT_SHA .
    - echo "IMAGE_TAG=$CI_COMMIT_SHORT_SHA" > build.env
  artifacts:
    reports:
      dotenv: build.env

smoke:
  stage: build
  image: alpine:3.22
  needs: [build-image]
  script:
    - echo "will deploy myapp:$IMAGE_TAG"
Push twice and compare the time:
git commit -am "ci: cache + reports" && git push
glab ci status --wait
glab ci trace "unit-test: [3.13]" | grep -E "Checking cache|cache|Uploading artifacts|TOTAL"
git commit --allow-empty -m "ci: rerun" && git push
glab ci status --wait
glab ci trace "unit-test: [3.13]" | grep -E "Checking cache|Successfully extracted|TOTAL"
# first run
Checking cache for pip-5c2e…-non_protected...
WARNING: file does not exist
Failed to extract cache
TOTAL                 12      0   100%
Creating cache pip-5c2e…-non_protected...
Uploading artifacts for successful job
# second run
Checking cache for pip-5c2e…-non_protected...
Successfully extracted cache
TOTAL                 12      0   100%

In the MR you can see a “test summary” (JUnit) and the coverage percentage; smoke the job prints will deploy myapp:8f3c2a1b.

Case 1: cache almost never hits on autoscaled Runners

Problem: Docker Autoscaler creates a new VM each time, so the local cache is always empty. Approach: Configure a [runners.cache] distributed cache (S3 / GCS / Azure Blob) that all Runners share. Limitations: Cache upload and download go over the network, so large caches must be compressed and cleaned up regularly; the distributed cache bucket must restrict access (the cache can be poisoned).

Case 2: deployed the “previous” build output

Problem: The deploy job reads from the cache dist/, and sometimes gets an old version. Approach: Switch to the build job's artifacts + needs: [build]; set expire_in: 1 week on artifacts to control storage cost.

Case 3: storage quota eaten up by artifacts

Problem: Every MR uploads 800 MB of test screenshots and logs, and the namespace exceeds its storage limit. Approach:artifacts:when: on_failure Save debugging material only on failure; expire_in: 3 days; clean up old artifacts (Build → Artifacts, bulk delete). Note:“Keep artifacts from most recent successful job” is on by default, so the latest artifacts never expire.

Common errors and fixes

WARNING: .cache/pip: no matching files. Ensure that the artifact path is relative to the working directory

Cause: The cache / artifact path does not exist: PIP_CACHE_DIR it was not set inside the project directory, or the path was written as an absolute path.

Fix:PIP_CACHE_DIR: "$CI_PROJECT_DIR/.cache/pip",paths use a relative path.

WARNING: file does not exist / Failed to extract cache

Cause: first run, key changed, Runner changed, or protected / unprotected cache isolation. This is a warning, not an error.

Fix: if misses persist, check the key, configure a distributed cache, or fallback_keys.

ERROR: Uploading artifacts as "archive" to coordinator... 413 Request Entity Too Large

Cause: the artifact exceeds the size limit (1 GB compressed on GitLab.com; on self-managed instances the administrator sets it).

Fix: use exclude to exclude unneeded files; put large files in a package registry / object storage.

deploy job: dist/ does not exist (ls: dist: No such file or directory)

Cause: deploy uses needs but does not include the job that produces dist; or the artifacts have expired; or the upstream dependencies: [].

glab ci trace deploy | grep -A3 "Downloading artifacts"

Fix: add build to needs; check expire_in.

JUnit report does not show in the MR

Cause: wrong path, the report is not JUnit XML, or no file was generated when the job failed (pytest exited before it could write it).

Fix: confirm that --junitxml=report.xml and reports:junit paths match. Report artifacts are always attempted for upload, pass or fail; check the log for “Uploading artifacts … junit”.

Command-line questions
1. Write a cache configuration for a test job that uses a read-only cache (no write-back).
cache:
  key:
    files: [requirements-dev.txt]
  paths: [.cache/pip]
  policy: pull
2. Download the artifacts of the latest unit-test job on the main branch.
glab job artifact main "unit-test: [3.13]"
Scenario analysis
The release job on main downloads all dependencies every time, while feature branch pipelines have a high cache hit rate. Both use the same key. Why? Should you “fix” it?

By default, “Use separate caches for protected branches” is on: the key for main (protected, triggered by a Maintainer) carries the -protected suffix, which differs from feature's -non_protected , so main always misses the first time and afterwards reuses the protected cache. This is a security design against cache poisoning, and turning it off is not recommended. If main runs rarely, accept a few misses, or use fallback_keys to point at a generic key that targets the protected cache.

Verified teaching videos

▶
DevOps with GitLab CI Course - Build Pipelines and Deploy to AWS — freeCodeCamp.org
English · course chapter covering artifacts and cache
▶
Gitlab CI pipeline tutorial for beginners — Valentin Despa
English · demo of passing artifacts between jobs

No dedicated walkthrough found cache:key:files / fallback_keys or verified video. Follow the official docs and this lesson as the authority.

Official docs

Video storyboard script (about 90 seconds)

Shot 1 · 0–25s
Visual: on the left, a storage locker labelled “maybe there” (cache); on the right, a locked parcel locker (artifacts).
Narration: cache is best-effort acceleration; artifacts are reliable result passing.
Shot 2 · 25–50s
Visual: a hash is computed from the requirements file and becomes the locker's number; change the file and the number changes.
Narration: use the contents of the dependency file as the cache key, so the cache is reused while dependencies do not change.
Shot 3 · 50–75s
Visual: the build job packs dist into the parcel locker, and deploy picks it up following the needs arrow.
Narration: pass build results as artifacts, and downstream jobs must list the upstream job in needs.
Shot 4 · 75–90s
Visual: two rows of lockers labelled protected and non_protected.
Narration: protected branches use separate caches by default, to prevent poisoning.
or score ≥ 70% in the quiz

Module 7 · include, templates and an introduction to CI/CD components

42:00 – 50:00 · include deep-merges several YAML files into one configuration; a component is an include with input parameters and a version, published in a catalog
8 minComponents and Catalog: Free (GA in 17.0)Going deeper: Lesson 5★★★★☆
Learning goals
  • Use five kinds of include: local,project,remote,template,component, and state each one's suitable scenarios and security differences.
  • Understand the merge rules: nested includes are merged first, a later include overrides an earlier one, and the main file is merged last. Hashes are deep-merged; arrays are replaced as a whole.
  • Write spec:inputs and use $[[ inputs.x ]] interpolation; reference official components from the CI/CD Catalog and pin their versions.
Prerequisites: extends and !reference from Module 2. Importance:★★★★☆ (component development and publishing is in Lesson 5)

What: the five kinds of include

TypeSyntaxSource and versionSuited to
localinclude: ci/python.yml or - local: ci/python.ymlsame repository, same commitsplitting a large configuration
project- project: mygroup-lab/ci-templates
  ref: v1.2.0
  file: /python.yml
other projects on the same instance; ref defaults to that project's HEADsharing templates within a team
remote- remote: https://…/ci.ymlpublic HTTP(S) URL; authentication not supported; integrity can verify the SHA256use with caution
template- template: Jobs/Secret-Detection.gitlab-ci.ymlbuilt-in GitLab templates; they change with GitLab versionstraditional access to official features
component- component: $CI_SERVER_FQDN/components/secret-detection/secret-detection@2.4.0published version of a component project; format <FQDN>/<project path>/<component name>@<version>the new recommended way to reuse

Limit: each pipeline allows at most 150 includes (including nested ones; adjustable on self-managed instances), and all must be parsed within 30 seconds. All includes can carry rules (use only if/exists/changes) and inputs.

How: merge rules (official “Merge method for include”)

  1. Includes are merged in the order they are written. If an included file has its own includes,the nested ones are merged first (recursively).
  2. When parameters overlap,the file merged later takes precedence.
  3. After all includes are merged,the main file .gitlab-ci.yml is merged on top; the main file has the highest precedence.
  4. Deep merge: if both sides are hashes, merge recursively; otherwise (including arrays, such as script and rules) the latter replaces the former as a whole.
  5. Variables are evaluated after all merging is complete, and the final value is decided by the Module 4 precedence.

What: CI/CD components

  • Component project: the root directory templates/ contains each <name>.yml or <name>/template.yml is a component, and it needs README.md; a project can have at most 100 components (raised from 30 in 18.5).
  • Input parameters: declared in the header of the component file spec:inputs (type, default, description, allowed values); after the separator comes --- the job definition, which uses $[[ inputs.stage ]] interpolation. If a required input is missing, the pipeline fails (an undefined variable just becomes empty, so inputs are safer).
  • Version: commit SHA > tag > branch name; ~latest some semantic versions (2 means the latest 2.*.*,2.4 means the latest 2.4.*) only match versions published in the Catalog. In production, pin the full version or the SHA.
  • CI/CD Catalog: the component project must enable “CI/CD Catalog resource” (Owner), have a description and a README, and publish semantic versions with the release keyword in CI; after that it appears in the catalog. Official components live in the gitlab.com/components group (for example sast,secret-detection,code-quality).

Why: why components are better than “copy and paste + templates”

Copy-and-paste makes dozens of projects drift apart; include:project without an interface contract, changing a template affects all projects at once; built-in template change as GitLab is upgraded. Components package the “interface (inputs) + implementation + version + documentation”, so users choose when to upgrade explicitly.

When: which to choose

  • Splitting within one repository: local.
  • Team sharing that needs versions: components (learn to publish in Lesson 5); during the transition, you can use project + with ref: tag.
  • Official security scanning: prefer gitlab.com/components components, or templates recommended by the docs.
  • remote: only from trusted sources, and pair it with integrity.

Comparison with similar technologies

GitLabGitHub ActionsAzure PipelinesJenkins
Reuse unitCI/CD components, includeAction, reusable workflowsYAML templates (template: + parameters)Shared Library
parametersspec:inputsinputsparametersfunction parameters
catalogCI/CD CatalogMarketplace— (the extension marketplace is for tasks)plugin hub
version pinning@1.2.3 / @SHA@v4 / @SHAref resources@Library('x@tag')
Common misconceptions① “Jobs brought in by include cannot be changed”: they can. Write a job with the same name in the main file to override it, or add hash fields (arrays must be rewritten in full). ② “~latest is convenient and safe”: when upstream publishes a new version, your pipeline changes, so pin the version in production. ③ “The rules in an include can use CI_JOB_* variables”: include is resolved before jobs are created, so only pipeline-level variables work.

Merge order illustration

① componentsecret-detection@2.4.0 ② local: ci/python.yml(nested includes are merged first) ③ project: ci-templatesref: v1.2.0 deep-merge in order① ← ② ← ③the later one overrides the earlier one .gitlab-ci.yml main filemerged last, highest precedence final configuration (Pipeline editor → Full configuration)hashes: deep-merged (variables, artifacts, cache)arrays: replaced as a whole (script, rules, needs)then: extends / !reference expandedthen: workflow:rules and job rules evaluated
Figure 7-1: include resolution is step 2 of the pipeline lifecycle and completes before any rules are evaluated

Component project structure

mygroup-lab/ci-components (created in Lesson 5) ├── templates/│ ├── pytest.yml ← component "pytest"│ └── docker-build/template.yml ← component "docker-build"├── README.md (required) LICENSE.md└── .gitlab-ci.yml (tests + release publishing) Consumer .gitlab-ci.yml include: - component: $CI_SERVER_FQDN/mygroup-lab/ci-components/pytest@1.0.0 inputs: stage: test python_version: "3.13"
Figure 7-2: a component = one file under templates/ + the spec:inputs interface + a semantic version

Interactive visualization: how include is merged into the final configuration

Tick the sources to include, then play step by step: GitLab fetches each file → interpolates inputs → deep-merges in order → merges the main file. On the right, the job is shown unit-test as it looks after each step.

Quick reference for syntax

include:
  - local: ci/python.yml                     # same repository
    inputs:
      python_version: "3.13"
  - project: mygroup-lab/ci-templates        # other project (pinned tag)
    ref: v1.2.0
    file: [/docker.yml]
  - template: Jobs/Secret-Detection.gitlab-ci.yml          # built-in template
  - component: $CI_SERVER_FQDN/components/sast/sast@3.5.0  # official component (pinned version)
    inputs:
      stage: test
  - local: ci/review.yml
    rules:
      - if: $CI_PIPELINE_SOURCE == "merge_request_event"
spec:
  inputs:
    python_version:
      default: "3.13"
      options: ["3.12", "3.13"]
    stage:
      default: test
---
python-unit:
  stage: $[[ inputs.stage ]]
  image: python:$[[ inputs.python_version ]]-slim
  script:
    - pip install -q -r requirements-dev.txt
    - pytest -q tests/test_app.py
ActionMethod
View the merged resultBuild → Pipeline editor → “Full configuration”
Validate a configuration that contains includesglab ci lint (server-side expansion)
Browse componentsSearch or Go to → Explore → CI/CD Catalog; or https://gitlab.com/explore/catalog
view the official component versionsglab release list -R components/secret-detection
glab release list -R components/secret-detection | head -3
Showing 3 releases on components/secret-detection
NAME    TAG     CREATED
2.4.0   2.4.0   about 3 months ago
…

Lab 7: split the configuration and integrate the official Secret Detection component (about 7 minutes)

Move the Python job into ci/python.yml (with input parameters):
mkdir -p ci
cat > ci/python.yml <<'EOF'
spec:
  inputs:
    stage:
      default: test
---
.python-job:
  variables:
    PIP_CACHE_DIR: "$CI_PROJECT_DIR/.cache/pip"
  cache:
    key:
      files: [requirements.txt, requirements-dev.txt]
      prefix: pip
    paths: [.cache/pip]
  before_script:
    - pip install -q -r requirements-dev.txt

python-lint:
  stage: $[[ inputs.stage ]]
  image: python:3.13-slim
  needs: []
  script:
    - pip install -q ruff
    - ruff check .
EOF
Add an include at the top of the main file, delete the original .python-job and lint jobs from the main file, and change the lint of the other jobs to needs python-lint:
include:
  - local: ci/python.yml
    inputs:
      stage: lint
  - component: $CI_SERVER_FQDN/components/secret-detection/secret-detection@2.4.0
    inputs:
      stage: lint
      enable_mr_pipelines: true
glab ci lint --dry-run --ref "$(git branch --show-current)" --include-jobs
git add ci .gitlab-ci.yml && git commit -m "ci: split config, add secret detection component" && git push
✓ CI/CD YAML is valid!
Jobs:
secret_detection
python-lint
unit-test: [3.12]
unit-test: [3.13]
integration-test
build-image
smoke

The component's enable_mr_pipelines input (default false) controls whether the scan job runs in MR pipelines. Our workflow keeps only MR pipelines, so set it to true. For the component's job name and inputs, follow the README of that version.

View the full configuration and scan results: in the pipeline editor's “Full configuration”, find the secret_detection job and confirm that stage: lint has been interpolated. The job produces a gl-secret-detection-report.json report artifact. Viewing results in the MR widget / security dashboard requires Ultimate; the Free tier can download the artifact and view the JSON.
glab job artifact "$(git branch --show-current)" secret_detection --path ./sd
python3 -m json.tool ./sd/gl-secret-detection-report.json | head -20
Verify the merge rules: in the main file, add a job with the same name that changes only stage:
python-lint:
  stage: test

In “Full configuration” you see python-lint 's stage changed to test, while script,image still come from the include: hashes are deep-merged, and the main file takes precedence. After confirming, delete these three lines.

Case 1: one template change makes 200 projects fail at once

Problem: Projects include: project do not specify ref, and the platform team renamed a variable in the template. Approach: migrate the template to a component and publish semantic versions; consumers pin @1.4.2; the platform team submits upgrade MRs through tools such as Renovate. Limitations: After pinning a version, security fixes require consumers to merge upgrade MRs. Partial versions (@1.4) can be combined to automatically accept only patch updates.

Case 2: a remote include was tampered with

Problem: The pipeline included a script template from a public URL; after that other repository was compromised, a command that steals variables was injected. Approach: Remove the remote include. If it must be used, set integrity: sha256-…, so a content change makes parsing fail; preferably mirror it into your own project and then publish it as a component.

Case 3: migrating from built-in templates to components

Problem: After a GitLab upgrade, the built-in template's behavior changed and a scan job name changed, causing needs failures. Approach: Switch to gitlab.com/components components with the same function and pin their versions; validate in an MR before upgrading.

Common errors and fixes

Local file `ci/python.yml` does not exist!

Cause: wrong path spelling, or the file exists locally but has not been committed to that commit (include reads the content at the pipeline's commit).

Fix: commit the file; write the path starting from the repository root.

`ci/python.yml`: unknown interpolation key: `stag`

Cause:$[[ inputs.stag ]] a spelling error, or the input is not declared in spec:inputs .

Fix: align the names. The interpolation syntax is $[[ inputs.name ]], not ${{ }}.

`ci/python.yml`: `stage` input: required value has not been provided

Cause: the input has no default, and none was provided at include time.

Fix: Add inputs: {stage: lint} to the include, or give a default value in the component.

Component 'gitlab.com/components/secret-detection/secret-detection@9.9.9' - content not found

Cause: the version does not exist, the component name is wrong, or a self-managed instance cannot reach gitlab.com for the component (components must come from the same instance; self-managed deployments must mirror the component project).

glab release list -R components/secret-detection
Maximum of 150 nested includes are allowed! (or include resolution timed out)

Cause: too many includes or too deep nesting, or a slow remote address.

Fix: merge small files, switch to components, and remove slow remote includes.

Command-line questions
1. Include the official SAST component version 3.5.0, with stage test.
include:
  - component: $CI_SERVER_FQDN/components/sast/sast@3.5.0
    inputs:
      stage: test
2. Include a review configuration file only in MR pipelines.
include:
  - local: ci/review.yml
    rules:
      - if: $CI_PIPELINE_SOURCE == "merge_request_event"
Scenario analysis
You include a template in which the test job has rules and script. In the main file you write test: {variables: {DEBUG: "1"}}, and the job's rules and script both remain, but when you write test: {script: [make check]} the original script is completely replaced. Why? How do you add only one line before the original script?

Include merging is a deep merge: hashes (variables) are merged, while arrays (script, rules) are replaced as a whole. To add one line before the original script, use script: [echo pre, !reference [.hidden-job-in-template, script]] (this requires the template to place script in a referenceable hidden job), or ask the template to provide before_script / input parameters. This is why components use inputs to expose extension points.

Verified teaching videos

▶
Talk: Efficient DevSecOps workflows with reusable CI/CD components — GitLab Unfiltered
English · talk referenced by the official component docs, introducing components and the Catalog
▶
NEW GitLab CI CD components explained — Christian Lempa
English · hands-on with components, inputs and the Catalog
▶
[Demo] Use of predefined project variables in `include` section of .gitlab-ci.yml — GitLab Unfiltered
English · short demo referenced by the official include docs

Official docs

Video storyboard script (about 90 seconds)

Shot 1 · 0–20s
Visual: five colour-coded YAML cards (local, project, remote, template, component) fly in.
Narration: include can assemble configuration from five kinds of sources.
Shot 2 · 20–50s
Visual: the cards stack in order, later ones covering earlier ones, with the main file on top. The script array is swapped out as a whole block, while variables are merged item by item.
Narration: the later merge takes precedence and the main file merges last; hashes are deep-merged, arrays are replaced as a whole.
Shot 3 · 50–75s
Visual: a component box with an inputs socket on its side and the version number 2.4.0.
Narration: a component packages the interface, implementation and version together, and takes parameters through inputs.
Shot 4 · 75–90s
Visual: the @~latest tag is crossed out and replaced with @2.4.0.
Narration: pin versions in production. In Lesson 5 you learn how to publish your own components.
or score ≥ 70% in the quiz

Module 8 · CI readiness review and common failures

50:00 – 60:00 · first work out which step of the lifecycle the failure happened in, then find the line in the log. The review checklist turns the first 7 modules into checkable standards
10 minInteractive troubleshooting tree★★★★★
Learning goals
  • Use the 10-item CI readiness checklist to review myapp's pipeline and set improvement priorities.
  • Classify any failure into a step of the lifecycle (configuration / rules / queueing / execution environment / script / cache and artifacts / status), and locate it with the matching command.
  • Use debugging tools safely (CI_DEBUG_TRACE exposes variables), and be able to reproduce and fix 4 typical kinds of failure.
Prerequisites: Modules 1–7. Importance:★★★★★

What: the CI readiness review checklist (10 items)

#DimensionStandardModule
1Reproducibleeach job explicitly specifies image (pinned to a major version or above), without relying on the hosted Runner's default ruby:3.1M2, M5
2Triggersworkflow:rules keep only MR pipelines plus default-branch / tag pipelines; no duplicate pipelinesM3
3Gatemain protected, with “pipeline must succeed” on for MRs; lint and tests run in MRsM3, Lesson 1
4SpeedMR pipelines under 10 minutes; use needs to shorten the critical path interruptible + auto_cancelM2, M3
5Cachedependency caching uses key:files; build results use artifacts, not cacheM6
6VisibilityJUnit and coverage reports go into the MR; save debugging artifacts on failure (when: on_failure)M6
7Secretsno plaintext secrets; deployment credentials are Protected + Masked (Hidden if possible), with a plan to migrate to OIDCM4, Lessons 3/4
8RunnerJobs use tags to declare placement explicitly; privileged or production-capable Runners are set to Protected and not sharedM5
9Reuseshared configuration is pinned to versions via components / include; no ~latest, and no unvalidated remote includesM7
10Reliabilityretry retry only for infrastructure failures; reasonable timeout; no tests that use allow_failure: true to hide failuresM1, M2

How: locate a failure by lifecycle step

Lifecycle stepTypical symptomWhere to lookTypical cause
2 Read / expand configurationPipeline fails immediately, marked “yaml invalid”Pipeline editor,glab ci lintspelling, indentation, include paths, inputs
3–4 RulesNo pipeline / missing job / one extra pipelineglab ci lint --dry-run --include-jobs, pipeline sourcefirst match,changes always true, needs referencing an excluded job
5–6 Queueing and claimingJob stays pending / stuck for a long timejob page notice,queued_duration, Runner listtags, protected Runner, Runner offline, compute minutes used up,concurrent
7 Execution environmentimage pull failure, services unreachable, runner system failurethe “Preparing environment” section of the logimage name / permissions, services aliases, dind privileges, disk full
7 ScriptERROR: Job failed: exit code 1output before the failing linetest failure, missing dependency, empty variable (protected variable)
8 Cache / artifactsfiles missing, upload failure“Saving cache / Uploading artifacts” sectionpath outside the project, needs not including the job, exceeds size
9 StatusMR cannot be merged / status not updatedMR widget, merge checksno MR pipeline, manual job blocking (default in rules for manual is allow_failure: false)

Why: classify first, then dig deeper

“The pipeline is red” could be a problem in any layer: configuration, rules, infrastructure or code. Reading hundreds of lines of log is very inefficient. First, based on whether there are jobs, the job status, and the log sections, determine which step failed, then use the tools for that step. This usually pinpoints the problem in 1–2 minutes.

When: safety boundaries of debugging tools

  • CI_DEBUG_TRACE: "true": prints every shell command and all variables (including masked secrets); use it only on private projects, on unprotected branches, and temporarily; delete the job log afterwards. For production projects, restrict it, for example by not granting Developers permission to view logs.
  • CI_DEBUG_SERVICES: "true": outputs the logs of service containers, for troubleshooting Redis / database service startup problems.
  • Collapsible log sections: echo -e "\e[0Ksection_start:$(date +%s):deps[collapsed=true]\r\e[0KInstall deps" … section_end, which makes long logs easier to read.

Comparison with similar technologies

GitLabGitHub ActionsAzure PipelinesJenkins
Syntax validationCI Lint / pipeline editor / glab ci lintactionlint (third-party)Editor validation / “Validate”Declarative Linter
Debug logsCI_DEBUG_TRACEACTIONS_STEP_DEBUGsystem.debugsh -x / log level
RetryUI / glab ci retry / retry:Re-run jobsRerun failed jobsReplay / retry()
Common misconceptions① “A pending job means GitLab is slow”: almost always a Runner matching or capacity issue. ② “Retrying fixes it”: this only works for infrastructure failures; for flaky tests, retries hide the problem. ③ “allow_failure: true makes the pipeline green”: it also lets failures be ignored, so limit it to non-critical checks and set an expiry date.

Failure classification: which step of the lifecycle

Configurationyaml invalid RulesNo pipeline / missing job Queueingpending / stuck Execution environmentImage / services / system Scriptexit code ≠ 0 Cache / artifacts / statusFiles missing / MR blocked glab ci lintFull configuration --dry-run--include-jobs Runner listqueued_duration Preparing sectionCI_DEBUG_SERVICES Context of the failing lineReproduce locally Uploading sectionMR merge checks Order of judgement: is there a pipeline? → is this job there? → did the job start running? → which section of the log did it fail in? If the answers to the first two questions are “no”, the problem is definitely not in the Runner or the script
Figure 8-1: failure location goes from left to right; the earlier it happens, the less you need to look at the job log

Interactive exercise: failure log classifier

Pick a real-format job log, decide for yourself which step of the lifecycle it belongs to, then click “Reveal”. The classifier highlights the key lines and gives the fix.


      

Troubleshooting commands

CommandPurpose
glab ci lint --dry-run --ref BRANCH --include-jobsConfiguration and rules layer: whether pipelines are created and which jobs exist
glab ci list --status failed --per-page 5Recent failed pipelines
glab ci trace JOB -b BRANCHView job logs
glab ci retry JOBRetry a single job
glab api "projects/:id/pipelines/ID/jobs?scope[]=failed"Failed job's failure_reason (such as script_failure,stuck_or_timeout_failure,runner_system_failure)
docker logs gitlab-runner / gitlab-runner verifySelf-managed Runner side issues
PIPE=$(glab api "projects/:id/pipelines?status=failed&per_page=1" | python3 -c 'import sys,json;print(json.load(sys.stdin)[0]["id"])')
glab api "projects/:id/pipelines/$PIPE/jobs?scope[]=failed" | python3 -c '
import sys,json
for j in json.load(sys.stdin):
    print(j["name"], j["status"], j["failure_reason"], j["web_url"])'
integration-test failed script_failure https://gitlab.com/mygroup-lab/myapp/-/jobs/9876543210

Temporarily turn on debugging (mind security)

integration-test:
  variables:
    CI_DEBUG_SERVICES: "true"   # service container logs
    # CI_DEBUG_TRACE: "true"    # prints all variables (including masked values); use only temporarily on branches without secrets

Lab 8: deliberately create 4 failures and fix them (about 8 minutes)

On branch feature/break-ci , introduce only one fault each time. After pushing, first classify it using the order of judgement from the diagram, then fix it.

cd ~/gitlablab/myapp && git switch feat/ci-pipeline && git switch -c feature/break-ci
git push -u origin feature/break-ci
glab mr create -b feat/ci-pipeline --fill --draft --yes   # the target is the CI branch, not main
Fault A: configuration layer— change the integration-test of script to scripts.
sed -i '/^integration-test:/,/^[a-z]/ s/^  script:/  scripts:/' .gitlab-ci.yml
glab ci lint
.gitlab-ci.yml is invalid
jobs:integration-test config contains unknown keys: scripts
jobs:integration-test script can't be blank

Fix: git checkout .gitlab-ci.yml. Lesson: lint before you push; a configuration error produces no job log at all.

Fault B: queueing layer— add smoke to tags: [lab-gpu], push, and the job stays pending with a notice that no Runner has the matching tag. Explain the reason with the Module 5 matching conditions, then delete that line.
Fault C: execution environment layer— change the integration-test's REDIS_HOST to redis-db (the service alias stays redis):
redis.exceptions.ConnectionError: Error -2 connecting to redis-db:6379. Name or service not known.
ERROR: Job failed: exit code 1

although it ends with exit code 1 (which looks like the script layer), the root cause is the service configuration. The “Starting service redis:8 …” line at the top of the log and the service alias are the clues. Fix: REDIS_HOST must match the service alias.

Fault D: rules / artifacts layer— add build-image a rule that runs it only on main, while smoke still needs: [build-image]:
'smoke' job needs 'build-image' job, but 'build-image' does not exist in the pipeline. This might be because of the only, except, or rules keywords.

Fix: smoke uses the same rules, or needs: [{job: build-image, optional: true}] (when optional, smoke gets no dotenv variables, so handle that in the script).

Wrap-up: after all fixes the pipeline turns green; close the draft MR and delete the branch:
glab mr close feature/break-ci
git switch feat/ci-pipeline && git branch -D feature/break-ci && git push origin --delete feature/break-ci
Add the CI checks to Lesson 1's review script ~/gitlablab/gitlab_ready.py (insert the 7 CI checks before ok = 0 ; the rest of the script stays unchanged):
cd ~/gitlablab && cp gitlab_ready.py gitlab_ready.py.bak
python3 - <<'PY'
from pathlib import Path
p = Path("gitlab_ready.py")
src = p.read_text(encoding="utf-8")
block = '''
# ---- Lesson 2: CI readiness checks ----
import base64
ci_file = api(f"projects/{P}/repository/files/.gitlab-ci.yml?ref=main")
raw = base64.b64decode(ci_file["content"]).decode("utf-8", "ignore") if ci_file else ""
pipes = api(f"projects/{P}/pipelines?ref=main&per_page=1") or []
runners = api(f"projects/{P}/runners?type=project_type") or []
civars = api(f"projects/{P}/variables") or []
checks += [
    ("CI", "main has a .gitlab-ci.yml", ci_file is not None),
    ("CI", "Merge check: pipeline must succeed", p.get("only_allow_merge_if_pipeline_succeeds") is True),
    ("CI", "Latest pipeline on main succeeded", bool(pipes) and pipes[0].get("status") == "success"),
    ("CI", "Configuration uses workflow:rules", "workflow:" in raw),
    ("CI", "include / components do not use ~latest", "~latest" not in raw),
    ("CI", "At least one project Runner is online", any(r.get("status") == "online" for r in runners)),
    ("CI", "All project CI/CD variables are Protected + Masked",
     all(v.get("protected") and v.get("masked") for v in civars)),
]
'''
if "Lesson 2: CI readiness 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 -9
[PASS] CI main has a .gitlab-ci.yml
[PASS] CI Merge check: pipeline must succeed
[PASS] CI Latest pipeline on main succeeded
[PASS] CI Configuration uses workflow:rules
[PASS] CI include / components do not use ~latest
[PASS] CI At least one project Runner is online
[PASS] CI All project CI/CD variables are Protected + Masked

Score 19/19 = 100%

If it runs before MR !2 of the comprehensive lab is merged, the first 3 CI checks will show FAIL (there is no CI configuration on main yet, and the merge check is not turned on). That is exactly the work the comprehensive lab completes. p is the project object already fetched by the original script. If the project has no CI/CD variables at all, the last check counts as a pass.

Back toModule 0 Redo the CI readiness self-assessment and compare with the pre-class score.

Case 1: every Monday morning, pipelines are all pending

Symptom: Many merges on Monday; jobs queue for over 15 minutes. Diagnosis: high queued_duration with all Runners online means a capacity problem; hosted Runners are normal means only jobs with the lab-docker tag are queueing. Fix: raise concurrent, add a second Runner and share the tag; in the long term, migrate to Docker Autoscaler (Lesson 7).

Case 2: a flaky test hidden by retry for half a year

Symptom: The integration test set retry: 2 (retry on all failures); with an 18% failure rate it always showed green. Fix: change it to retry: {max: 2, when: [runner_system_failure, stuck_or_timeout_failure]}; use the JUnit report to find the flaky cases, then isolate and fix them.

Case 3: debugging logs leaked secrets

Symptom: To troubleshoot a deployment problem, CI_DEBUG_TRACE was turned on on main, and the log showed all variables. Handling: delete the job logs and rotate all exposed secrets. Afterwards, agree that debugging is done only on branches without secrets, and change deployment credentials to OIDC.

Interactive troubleshooting tree: locate issues step by step from symptoms

The troubleshooting tree covers common failures across all modules in this lesson; the commands in the diagnosis results can be copied directly.

Command-line questions
1. Find the failure_reason of each failed job in the most recent failed pipeline.
PIPE=$(glab api "projects/:id/pipelines?status=failed&per_page=1" | python3 -c 'import sys,json;print(json.load(sys.stdin)[0]["id"])')
glab api "projects/:id/pipelines/$PIPE/jobs?scope[]=failed" | python3 -c 'import sys,json;[print(j["name"],j["failure_reason"]) for j in json.load(sys.stdin)]'
2. Before pushing, confirm that the configuration on the feature/x branch is valid, and list its jobs.
glab ci lint --dry-run --ref feature/x --include-jobs
Scenario analysis
A new colleague says: “My MR keeps showing waiting for pipeline. I have pushed many times, but my branch does not appear in the pipeline list.” Give the troubleshooting steps in the order of judgement.

① Is there a pipeline? No → the problem is in the configuration / rules layer, not the Runner. ②glab ci lint check the syntax; ③glab ci lint --dry-run --ref branch --include-jobs to see whether it says “filtered out by workflow rules” or the job list is empty; ④ check whether the workflow rules include merge_request_event, and whether the commit message contains [skip ci]; ⑤ if merged results are enabled but there are no MR rules, the MR will wait forever. After fixing, push and confirm that an MR pipeline appears.

Verified teaching videos

▶
Learn GitLab in 3 Hours | GitLab Complete Tutorial For Beginners — TestMu AI (Formerly LambdaTest)
English · long comprehensive tutorial, useful as an overall review of this lesson

No dedicated, verified video on troubleshooting GitLab CI failures was found; use this lesson's troubleshooting tree and the official docs as the authority.

Official docs

Video storyboard script (about 90 seconds)

Shot 1 · 0–20s
Visual: a red pipeline with four question bubbles beside it: is there a pipeline? are there jobs? did it start? which section failed?
Narration: classify first, then dig deeper. Four questions can pin a failure to one step of the lifecycle.
Shot 2 · 20–45s
Visual: a YAML card is marked with a red cross by lint; another card is blocked outside the workflow gate.
Narration: configuration and rules problems produce no job logs, so check them with lint and dry run.
Shot 3 · 45–70s
Visual: a job card spins in the queue, and none of the Runners' tags match it.
Narration: a pending job is almost always a Runner matching or capacity problem.
Shot 4 · 70–90s
Visual: the 10 review items are ticked off one by one.
Narration: review the pipeline against a ten-item readiness checklist, and turn quick fixes into long-term standards.
or score ≥ 70% in the quiz

Command cheat sheet

A one-page summary of all keywords, commands and predefined variables in this lesson (GitLab 19.5.x / Runner 19.5.3 / glab 1.130)
.gitlab-ci.yml skeleton
include: [ … ]            # local / project / remote / template / component
workflow: { name, auto_cancel, rules }
stages: [lint, test, build]
default: { image, interruptible, retry, … }
variables: { KEY: "value" }

job:
  stage: test
  image: python:3.13-slim
  services: [{ name: redis:8, alias: redis }]
  tags: [lab-docker]
  needs: [other]           # [] = start immediately
  rules: [ { if, changes, exists, when } ]
  script: [ … ]
  cache: { key: { files: [ … ] }, paths: [ … ], policy }
  artifacts: { paths, expire_in, when, reports }
  parallel: { matrix: [ { PY: ["3.12","3.13"] } ] }
  retry: { max: 2, when: [runner_system_failure] }
  timeout: 30m
  interruptible: true
glab commands
glab ci lint [--dry-run --ref B --include-jobs]Validate / simulate
glab ci status [--live|--wait]Current branch status
glab ci viewInteractive view
glab ci list [--status failed] [--source …]Pipeline list
glab ci trace JOB [-b B]Job log
glab ci run -b B [--variables K:V] [--mr]Manual run
glab ci retry JOB / glab ci cancelRetry / cancel
glab variable set K -v V [-p -m --hidden -r -t file -s ENV -g GROUP]Variables
glab job artifact REF JOB [--path DIR]Download artifacts
glab release list -R components/NAMEComponent versions
Common rules conditions
MR pipeline$CI_PIPELINE_SOURCE == "merge_request_event"
Default branch$CI_COMMIT_BRANCH == $CI_DEFAULT_BRANCH
Tag$CI_COMMIT_TAG
Push to a branch with an open MR$CI_COMMIT_BRANCH && $CI_OPEN_MERGE_REQUESTS
Scheduled run$CI_PIPELINE_SOURCE == "schedule"
Draft MR$CI_MERGE_REQUEST_DRAFT == "true"
MR types$CI_MERGE_REQUEST_EVENT_TYPE: detached / merged_result / merge_train

First match takes effect; no match means not added; in rules, when: manual defaults to allow_failure: false.

Runner (Docker)
docker run -d --name gitlab-runner --restart always \
  -v "$HOME/gitlablab/runner:/etc/gitlab-runner" \
  -v /var/run/docker.sock:/var/run/docker.sock \
  gitlab/gitlab-runner:v19.5.3
docker exec gitlab-runner gitlab-runner register --non-interactive \
  --url https://gitlab.com --token "$RUNNER_TOKEN" \
  --executor docker --docker-image alpine:3.22 \
  --docker-privileged --docker-volumes /certs/client \
  --description lab-docker-runner
docker exec gitlab-runner gitlab-runner verify
docker exec gitlab-runner gitlab-runner list

Tags, Run untagged and Protected are set in the UI / API; concurrent is in config.toml.

cache vs artifacts
cacheartifacts
StorageRunner local / distributedGitLab
ReliableNoYes
Default lifetimeuntil overwritten / cleaned up (hosted Runner caches are deleted after 14 days without updates)30 days (GitLab.com)
PurposeDependency downloadsBuild results, reports, dotenv
Variable precedence (high → low)

Policy variables → manual job → pipeline variables → project → group → instance → dotenv → YAML (rules > job > workflow > top level) → deployment → predefined

Protection options

Protected: injected only into protected branches / tags · Masked (default from 18.3): replaced with [MASKED] in logs; ≥ 8 characters, single line, no spaces · Masked and hidden: cannot be viewed after creation · File: the variable value is a file path

Common predefined variables

CI_PIPELINE_SOURCE · CI_COMMIT_BRANCH · CI_COMMIT_TAG · CI_COMMIT_SHORT_SHA · CI_COMMIT_REF_SLUG · CI_COMMIT_REF_PROTECTED · CI_DEFAULT_BRANCH · CI_MERGE_REQUEST_IID · CI_MERGE_REQUEST_SOURCE_BRANCH_NAME · CI_OPEN_MERGE_REQUESTS · CI_REGISTRY · CI_REGISTRY_IMAGE · CI_REGISTRY_USER · CI_REGISTRY_PASSWORD · CI_JOB_TOKEN · CI_SERVER_FQDN · CI_PROJECT_DIR · CI_JOB_NAME_SLUG

Hosted Runners and limits (GitLab.com)

Untagged → saas-linux-small-amd64 (2 vCPU / 8 GB) · default image ruby:3.1 · Free: 400 compute minutes per month · project default job timeout 1 hour (hosted Runner hard limit 3 hours) · 1 GB per artifact · needs up to 50 · at most 150 includes · parallel 1–200 · up to 4 caches per job · Free: up to 500 jobs per pipeline

Comprehensive lab + graduation quiz

Build a “production-ready” CI for myapp: MR gate, cache and reports, component scanning, and a self-managed Runner that builds the image and pushes it to the GitLab Container Registry
After class ≈ 35 minIntegrate all modules
Scenario The team decides that all changes to myapp are merged into main via MR. Review requirements: lint, unit tests (two Python versions), the Redis integration test and Secret Detection run automatically in MRs, with test and coverage results shown in the MR; no duplicate pipelines; after merging to main, build the image on a self-managed Runner and push it to registry.gitlab.com/mygroup-lab/myapp:<short SHA>, and tag a release v1.0 ; push the image again when the release tag is created :1.0 (remove the v prefix from the image tag); after pushing, run a health check using the image itself (port 5000,/healthz).
Cost: hosted Runners use about 10–15 compute minutes; the Container Registry uses a small amount of namespace storage. Permissions: Project Maintainer. Risk: privileged Runners are used only for lab projects.
Pre-flight checks (Modules 0, 5, 7)
cd ~/gitlablab/myapp && git switch feat/ci-pipeline && git pull
ls ci/python.yml tests/test_app.py tests/test_redis.py Dockerfile
docker exec gitlab-runner gitlab-runner verify
glab api projects/:id | python3 -c 'import sys,json;p=json.load(sys.stdin);print(p["path_with_namespace"], p.get("container_registry_access_level"))'
ci/python.yml  Dockerfile  tests/test_app.py  tests/test_redis.py
Verifying runner... is valid
mygroup-lab/myapp enabled

If a file is missing, go back to the “Lab” page of the corresponding module and create it. If the Container Registry is turned off, turn it on under Settings → General → Visibility, project features and permissions.

Write the complete .gitlab-ci.yml (Modules 2, 3, 4, 5, 6, 7)
include:
  - local: ci/python.yml
    inputs:
      stage: lint
  - component: $CI_SERVER_FQDN/components/secret-detection/secret-detection@2.4.0
    inputs:
      stage: lint
      enable_mr_pipelines: true

workflow:
  name: "$CI_PIPELINE_SOURCE · $CI_COMMIT_REF_NAME"
  auto_cancel:
    on_new_commit: interruptible
  rules:
    - if: $CI_PIPELINE_SOURCE == "merge_request_event"
    - if: $CI_COMMIT_BRANCH && $CI_OPEN_MERGE_REQUESTS
      when: never
    - if: $CI_COMMIT_BRANCH
    - if: $CI_COMMIT_TAG

stages: [lint, test, build, verify]

default:
  image: python:3.13-slim
  interruptible: true
  retry:
    max: 2
    when: [runner_system_failure, stuck_or_timeout_failure]

unit-test:
  stage: test
  extends: .python-job
  needs: [python-lint]
  parallel:
    matrix:
      - PY: ["3.12", "3.13"]
  image: python:${PY}-slim
  script:
    - pytest -q tests/test_app.py --junitxml=report.xml --cov=app --cov-report=term --cov-report=xml
  coverage: '/TOTAL.*? (\d+(?:\.\d+)?)%/'
  artifacts:
    when: always
    expire_in: 1 week
    reports:
      junit: report.xml
      coverage_report:
        coverage_format: cobertura
        path: coverage.xml

integration-test:
  stage: test
  extends: .python-job
  tags: [lab-docker]
  needs: [python-lint]
  services:
    - name: redis:8
      alias: redis
  variables:
    REDIS_HOST: redis
  script:
    - pytest -q tests/test_redis.py --junitxml=report-redis.xml
  artifacts:
    when: always
    reports:
      junit: report-redis.xml

build-image:
  stage: build
  image: docker:29
  services: [docker:29-dind]
  tags: [lab-docker]
  needs: [unit-test]
  variables:
    DOCKER_TLS_CERTDIR: "/certs"
    IMAGE: $CI_REGISTRY_IMAGE:$CI_COMMIT_SHORT_SHA
  rules:
    - if: $CI_PIPELINE_SOURCE == "merge_request_event"
      changes:
        paths: [Dockerfile, "**/*.py", "requirements*.txt"]
    - if: $CI_COMMIT_BRANCH == $CI_DEFAULT_BRANCH
    - if: $CI_COMMIT_TAG =~ /^v\d+\.\d+/
  script:
    - docker build --pull -t "$IMAGE" .
    - docker run --rm "$IMAGE" python -c "import app; print('import ok')"
    - |
      if [ "$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" "$CI_REGISTRY_IMAGE:${CI_COMMIT_TAG#v}"   # v1.0 → 1.0
          docker push "$CI_REGISTRY_IMAGE:${CI_COMMIT_TAG#v}"
        fi
      fi

smoke:
  stage: verify
  image: $CI_REGISTRY_IMAGE:$CI_COMMIT_SHORT_SHA
  needs: [build-image]
  rules:
    - if: $CI_COMMIT_BRANCH == $CI_DEFAULT_BRANCH
    - if: $CI_COMMIT_TAG =~ /^v\d+\.\d+/
  script:
    - cd /app
    - gunicorn -b 127.0.0.1:5000 app:app --daemon
    - sleep 3
    - python -c "import urllib.request as u; r=u.urlopen('http://127.0.0.1:5000/healthz'); print(r.status, r.read().decode())"

smoke Run directly with the just-pushed image as the job image. The Runner logs in to the GitLab Container Registry automatically with the job credentials to pull the private image. build-image In MRs, build but do not push, so unreviewed code does not enter the image registry.

enable “pipeline must succeed” and merge via MR !2 (closing Issue #2)
git add -A && git commit -m "ci: production-ready pipeline"
git push
# the merge check that Lesson 1 deliberately left off: Settings → Merge requests → Merge checks → “Pipeline must succeed”
glab api --method PUT "projects/:id" -f only_allow_merge_if_pipeline_succeeds=true   | python3 -c 'import sys,json;print(json.load(sys.stdin)["only_allow_merge_if_pipeline_succeeds"])'
glab mr update 2 --ready
glab ci status --wait
True
- Marking merge request !2 as ready
(success) • 3m 05s   refs/merge-requests/2/head
┌ lint ── ✓ python-lint  ✓ secret_detection
├ test ── ✓ unit-test: [3.12]  ✓ unit-test: [3.13]  ✓ integration-test
└ build ─ ✓ build-image

On the MR page, confirm: there is only one MR pipeline; the test summary shows 2 + 1 reports; the coverage percentage appears. The MR description's Closes #2 will close Issue #2 after merging. Merged by a Maintainer: glab mr merge 2 --yes (or merge in the UI; main only allows Maintainers to merge).

Verify the main pipeline and image
git switch main && git pull
glab ci status --wait
glab ci trace smoke | tail -3
glab api "projects/:id/registry/repositories?tags=true" | python3 -c 'import sys,json;[print(r["location"],[t["name"] for t in r.get("tags",[])]) for r in json.load(sys.stdin)]'
200 ok
Job succeeded
registry.gitlab.com/mygroup-lab/myapp ['8f3c2a1b']
Release tag v1.0 (image tag 1.0)
git tag v1.0 && git push origin v1.0
glab ci status -b v1.0 --wait
docker pull registry.gitlab.com/mygroup-lab/myapp:1.0   # run docker login registry.gitlab.com first

Lesson 1 set all tags as protected (only Maintainers can create them), so the v1.0 tag pipeline runs on a protected ref, where protected variables and protected Runners are both available. The Lesson 3 deployment credentials depend on exactly this.

Review and cleanup: run python3 ~/gitlablab/gitlab_ready.py "$GL_PROJECT" (Module 8 has added the CI checks), target 19/19; then go back toModule 0 and redo the self-assessment, target 8 items or more. The image, Runner and project are kept for Lesson 3 (Azure). To clean up: delete the test tags under Deploy → Container Registry; delete the Runner under Settings → CI/CD → Runners and docker rm -f gitlab-runner; delete the CI/CD variables created in this lesson.
Acceptance checklist

Open-ended self-test (answer first, then expand the reference answer)

1. In order, state the 9 steps of a pipeline from push to a green check on the MR.

Event → read and expand YAML (include, extends, inputs) → workflow:rules → job rules → job enters the pending queue → Runner long-polls jobs/request and claims it by tags / protection and other conditions → executor prepares the environment, clones, restores cache, downloads artifacts, runs the script → saves cache, uploads artifacts and logs → Runner reports status, and GitLab updates the pipeline, commit status and MR.

2. What are the two effects that needs has on a job?

Execution order: it waits only for the listed jobs, instead of the whole previous stage. Artifacts: it downloads only the artifacts of the listed jobs (needs:artifacts default true).

3. Why does one push produce two pipelines, and how do you fix it?

The job rules match both push and merge_request_event. Use the official workflow rules: MR events run; never when the branch has an open MR; pushes to other branches run.

4. What do Protected and Masked each protect, and what else is needed?

Protected means only pipelines on protected branches / tags can get the variable; Masked only replaces the full value in logs. You also need to restrict who can push to protected branches, review changes to the CI configuration, avoid debugging logs, and move to short-lived OIDC credentials or external secret management.

5. How does the new Runner registration flow differ from the old one?

The new flow first creates the Runner in GitLab (via the UI or POST /user/runners), which gives you an glrt- authentication token, and then gitlab-runner register --token; tags, protection and similar settings are managed by the server, and passing them on the command line causes an error. The old registration token flow is deprecated and planned for removal in GitLab 20.0.

6. When include merges, which takes precedence: the main file, the earlier-included file or the later-included file? How are arrays handled?

Nested includes are merged first; a later include overrides an earlier one; the main file is merged last and has the highest precedence. Hashes are deep-merged; arrays (script, rules, etc.) are replaced as a whole.

Graduation quiz (12 questions, covering all modules)

Sources and version notes

Verification basis for all technical facts in this lesson (verified on 2026-11-16)

Versions and releases

FactValueSourceVerified on
Latest GitLab minor version19.5 (released 2026-10-15; latest patch 19.5.6, tagged 2026-11-16); 19.6 is not yet released (the release notes page shows it as Upcoming)GitLab 19.5 release notes; gitlab-org/gitlab repository tag v19.5.6-ee2026-11-16
Latest GitLab Runner versionv19.5.3 (2026-11-05)gitlab-runner CHANGELOG; Docker Hub tag gitlab/gitlab-runner:v19.5.32026-11-16
Latest glab versionv1.130.0 (2026-11-10)gitlab-org/cli releases2026-11-16
GitLab Secrets ManagerGA in 19.5; Premium / Ultimate, add-on19.5 release notes2026-11-16
Official component versionssecret-detection 2.4.0; sast 3.5.0gitlab.com/components2026-11-16

CI/CD keywords and behavior

TopicFacts used in this lessonSource
Global keywords, default, needs, rules, parallel, retry, cache, artifactsneeds ≤ 50, can be in the same stage,needs: []; rules: first match, no match → not added, manual in rules defaults to allow_failure false; changes is always true when there is no push event; parallel 1–200; retry max 0–2; cache up to 4 per job, key:files defaults to 2 files (feature flag up to 10 in 19.5); extends up to 11 levels; stage defaults to test when unspecifiedCI/CD YAML syntax reference
workflowwhen in workflow:rules can only be always / never; values of auto_cancel:on_new_commit; official de-duplication rulesworkflow
Pipeline sources and MR typesfull CI_PIPELINE_SOURCE table; CI_MERGE_REQUEST_EVENT_TYPE = detached / merged_result / merge_trainJob rules,Predefined variables
merged result pipelines / merge trainsPremium / Ultimate; MR pipelines must be configured, otherwise the MR may get stuckMerged results pipelines,Merge trains
Variablesten-level precedence; Masked requirements; default visibility is Masked from 18.3; Hidden: project / group GA in 17.6, instance 19.0; group environment scope Premium; conditions for MR pipelines to access protected variables (18.1); for new projects in new GitLab.com namespaces, the pipeline variables default is no_one_allowedCI/CD variables,MR pipelines
Runner registrationglrt- authentication token; register --token; server-managed parameters passed in cause FATAL; the old registration token is planned for removal in 20.0; compatibility mode since 16.2Registering runners; gitlab-runner source code commands/register.go
Runner configuration and pollingcheck_interval default 3 seconds; Workhorse long polling default 50 seconds; request_concurrency default 1; pull_policy default alwaysAdvanced configuration
Executor statusDocker, Docker Autoscaler, Instance, Kubernetes active; Shell, SSH, VirtualBox, Parallels, Custom in maintenance mode; Docker Machine deprecatedExecutors
Hosted Runnersmachine types and tags; untagged uses small; default image ruby:3.1; GCS distributed cache 14 days, 5 GB each; temporary VMHosted runners on Linux,Hosted runners
Compute minutes and limitsFree 400 minutes per month; Small factor 1; GitLab.com artifacts 1 GB, 30 days expiry; Free 500 jobs per pipeline; project default job timeout 1 hour; hosted Runner jobs last at most 3 hours (not affected by project settings)Compute minutes,GitLab.com settings,Pipeline settings
Identity verificationemail / phone / credit card verification required based on risk; cards are not charged or storedIdentity verification
Cache and artifactsprotected cache suffix; clearing the cache requires Developer; artifacts default to 30 daysCaching,Job artifacts
include and components150 includes, 30 seconds; merge order; component format, version priority, ~latest, 100 components per project (18.5), Catalog publishing requirements, GA in 17.0Includes,CI/CD components
glab commands and argumentsci lint/status/list/trace/run/retry/view, variable set, job artifact, repo create, release listglab docs/source
Runner APIPOST /user/runners,runner_type,tag_list,run_untagged, the token needs the create_runner scopeUsers API

Video verification notes

All videos had their titles and channels verified on 2026-11-16 via YouTube oEmbed (https://www.youtube.com/oembed?url=…&format=json) — titles and channels checked:

No dedicated, verified videos were found for Module 3 (rules), Module 6 (cache details) and Module 8 (troubleshooting); this is noted on the corresponding pages, and storyboard scripts are provided. Most videos were recorded earlier (registration tokens, only/except, older UI); where they conflict with this lesson, this lesson and the official docs take precedence.

Narration notes

The “Narration” page uses the browser's built-in Web Speech API: Chinese narration uses the zh-CN voice, and English terms use the en-US voice. The course page contains no audio files; the narration scripts can be used directly for TTS or as recording scripts. On Windows, you can add a Chinese (Simplified) voice pack under Settings → Time & language → Speech.

Known limitations

  • The commands in this course page were not actually run on a real GitLab.com project; all “expected output” is example output written in the format of the official docs. Pipeline / job / project IDs, SHAs, times, Runner names and durations are sample values.
  • glab's output format changes between versions; take the names of Runner log sections from the actual log.
  • Hosted Runner authentication requirements, the compute-minute quota and machine types may change; check the current page on docs.gitlab.com.
  • Version for “Masked and hidden”: project / group level GA in 17.6; instance level introduced in 19.0 (different sections of the docs record this separately).
  • The inputs and job names of the Secret Detection component follow version 2.4.0; new versions may change them. Viewing scan results in the MR requires Ultimate.
  • Merged result pipelines and merge trains require Premium / Ultimate; this lesson gives Free-tier alternatives.
  • Self-managed Runners that use privileged mode and the Docker socket are only for lab environments; production hardening is covered in Lessons 6 and 7.