GitLab Hour 2: GitLab CI/CD Core
- 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 useneedsto turn the pipeline into a DAG (directed acyclic graph). - Master
rulesandworkflow: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 Dockergitlab-runner(tagslab-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
| # | Time | Module | Core content | Animation / interaction | Lab (project mygroup-lab/myapp) |
|---|---|---|---|---|---|
| 0 | Before class | Warm-up and bridge | Fill in myapp's tests and dependencies, and commit the first .gitlab-ci.yml | CI readiness self-assessment (10 items) | First green pipeline |
| 1 | 00–06 | CI/CD architecture | Pipelines, stages, jobs, Runners, executors; job state machine; hosted vs self-managed | Core animation: the lifecycle of one pipeline run | Reading each stage of a job log |
| 2 | 06–13 | .gitlab-ci.yml syntax | stages, jobs, image, services, default, needs (DAG), parallel:matrix | Stage order vs DAG Gantt chart | lint → test → build, using needs to go faster |
| 3 | 13–21 | rules, workflow and pipeline types | rules:if/changes/exists, workflow:rules, MR pipelines, merged results, duplicate pipelines | rules evaluator | Only run on MRs and main |
| 4 | 21–28 | Variables and protected variables | Predefined variables, precedence, Protected / Masked / Hidden, File type | Variable precedence resolution + log masking | glab variable set |
| 5 | 28–35 | Runner | GitLab-hosted Runner machine types and compute minutes, self-managed registration (glrt-), executors, tags | Job-to-Runner matching simulator | Running in Docker gitlab-runner |
| 6 | 35–42 | Cache and artifacts | cache:key:files, fallback_keys, policy; artifacts, reports, expire_in, dependencies | Cache hits / artifact passing across two pipeline runs | pip cache + JUnit report |
| 7 | 42–50 | include, templates and components | local/project/remote/template/component, spec:inputs, CI/CD Catalog | include merge visualization | Adding the Secret Detection component |
| 8 | 50–60 | CI readiness review and common failures | Review checklist, locating job logs, common errors | Failure log classifier + troubleshooting tree | Deliberately trigger 4 kinds of failure and fix them |
| — | After class | Cheat sheet · Comprehensive lab | Full myapp CI: MR gate + self-managed Runner building the image and pushing it to the GitLab Container Registry | Graduation quiz (12 questions) | Comprehensive lab |
Knowledge Coverage Matrix
| Target skill | M1 | M2 | M3 | M4 | M5 | M6 | M7 | M8 | Key commands / keywords | Lab |
|---|---|---|---|---|---|---|---|---|---|---|
| Explain the whole pipeline process, from event to status | ✓ | · | ✓ | · | ✓ | ✓ | · | ✓ | glab ci view, job logs | M1 lab |
| Write .gitlab-ci.yml and a DAG | · | ✓ | · | · | · | ✓ | ✓ | ✓ | stages,needs,glab ci lint | lint/test/build |
| Control when jobs run (rules / workflow) | · | · | ✓ | · | · | · | ✓ | ✓ | rules:if,CI_PIPELINE_SOURCE | MR pipeline |
| Use variables and secrets safely | · | · | · | ✓ | ✓ | · | · | ✓ | glab variable set -m -p | Protected variables |
| Choose and register a Runner | ✓ | · | · | · | ✓ | ✓ | · | ✓ | gitlab-runner register --token | Docker Runner |
| Speed up with cache and pass results with artifacts | ✓ | ✓ | · | · | · | ✓ | · | ✓ | cache:key:files,artifacts:reports | pip cache |
| Reuse configuration (include / components) | · | · | · | · | · | · | ✓ | ✓ | include:component,spec:inputs | Secret Detection |
| Locate and fix CI failures | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | glab ci trace,CI_DEBUG_TRACE | M8 failure drill |
What this lesson does not cover (and where to learn it)
| Topic | Why it is not in this lesson | Where to learn it |
|---|---|---|
| Protected branches, approval rules, push rules, repository mirroring | Belongs to repository and collaboration governance, which the Git course covers | Git Lesson 4,GitLab Lesson 1 |
OIDC (id_tokens) deploying to Azure / AWS and pushing container images to cloud registries | Needs a cloud account, so it is a separate lesson | Lesson 3 (Azure),Lesson 4 (AWS) |
| Component development and publishing, parent-child and multi-project pipelines, merge trains, environments and deployment approvals | Belongs to “production-grade pipelines” | Lesson 5 |
| Security scan result governance, compliance pipelines, pipeline execution policies | Requires Ultimate; it is a governance topic | Lesson 6 |
| Runner autoscaling (Docker Autoscaler, Kubernetes executor), performance tuning | Beyond 1 hour | Lesson 7 |
| How to write GitHub Actions / Azure Pipelines / Jenkins | This lesson only covers a conceptual comparison | GitHub Actions core · Azure Pipelines core · Jenkins Pipeline core |
How to use this course material
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.
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).
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.
Module 0 · Warm-up and bridge: your first .gitlab-ci.yml
- Completed GitLab Lesson 1: a GitLab.com free account, top-level group
mygroup-lab(that is, your${GL_USER}-lab) group, projectmygroup-lab/myapp, with the local clone at~/gitlablab/myapp; environment variablesGL_USER,GL_GROUP,GL_PROJECTare set;glab auth statusshows you are logged in. - myapp already has:
app.py(Flask,/returns the Redis counterhitsas JSON,REDIS_HOSTdefaultredis;/healthzadded by MR !1, returns plain textok),requirements.txt,requirements-dev.txt,tests/test_app.py, based onpython:3.13-slim, running gunicorn as non-root UID 10001 (0.0.0.0:5000) in theDockerfile,.gitlab/CODEOWNERSand the MR template. mainProtected: 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.
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.
Module 1 · CI/CD architecture: how pipelines, jobs and Runners work
- 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.
What: what GitLab CI/CD is made of
| Concept | What it is | Where it is defined / runs |
|---|---|---|
| Pipeline | One CI/CD run containing several jobs, with its own ID, source (CI_PIPELINE_SOURCE) and status | Created by the GitLab server, based on events and .gitlab-ci.yml . |
| Stage | Groups 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 succeed | stages: (default .pre, build, test, deploy,.post) |
| Job | The smallest unit of execution: a group of script commands + an execution environment (image, variables, cache, artifacts) | Any non-reserved top-level key in YAML |
| Runner | A gitlab-runner program: an agent that requests jobs from GitLab, runs them and reports the results back | GitLab-hosted (GitLab.com) or self-managed (your machine / cluster) |
| Executor | How 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
- 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. - Read and expand the configuration: a GitLab background job (Sidekiq) reads the
.gitlab-ci.ymlof that commit and expandsinclude(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”. - workflow:rules evaluation: decides whether to create this pipeline. If no rule matches, the pipeline is not created.
- Job rules evaluation: for each job, check the
rulesentries in order; the first matching rule decides whether the job joins the pipeline, and itswhen,allow_failure, andvariables; if none match, the job is not added. - Queueing: jobs that can start enter the
pendingstatus, waiting for a matching Runner (tags, whether it is protected, whether the project has that Runner enabled). - Runner polling and claiming: the Runner polls every
check_interval(3 seconds by default) and callsPOST /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). - 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). - 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). - Status reporting: the Runner uses
PUT /api/v4/jobs/:idto 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 | |
|---|---|---|
| Maintenance | Handled by GitLab; a fresh temporary VM for each job | You handle installation, upgrades, scaling and cleanup |
| Billing | Consumes 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 |
| Network | Public internet; cannot reach your private network | Can reach your private network, private repositories and databases |
| Suited to | open-source projects, typical build and test work, getting started | special hardware / GPUs / private-network access / large volumes of minutes / compliance isolation |
Comparison with similar technologies (see the relevant course)
| GitLab CI/CD | GitHub Actions | Azure Pipelines | Jenkins | |
|---|---|---|---|---|
| Config file | one .gitlab-ci.yml at the root (can be included) | .github/workflows/*.yml Multiple workflows | azure-pipelines.yml | Jenkinsfile (Groovy DSL) |
| Execution agent | Runner (pull) | Runner (pull) | Agent (pull) | Agent (controller schedules; inbound or outbound JNLP) |
| Reuse unit | include, CI/CD components | Actions, reusable workflows | templates | Shared Library |
| Dependency graph | stages + needs | needs | dependsOn | stage order + parallel |
needs , jobs can start early across stages (Module 2).Architecture diagram: GitLab control plane and Runner execution plane
Sequence diagram: API round trip for one job
CI_JOB_TOKENCore 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
| Command | Purpose | Key arguments / notes |
|---|---|---|
glab ci lint | Validate 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 status | Status of the latest pipeline on the current branch | -b branch,--live live refresh |
glab ci view | Interactively view pipelines, jobs and logs | Jobs can be retried or cancelled in the UI |
glab ci list | List pipelines | --status failed,--source merge_request_event |
glab ci trace | Follow the log of a job | job name or ID |
glab ci run | Manually create a pipeline (source api) | -b main,--variables KEY:VALUE,--mr |
glab ci retry / cancel | Retry / cancel a job or pipeline | Requires 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)
api), and note the pipeline ID:
cd ~/gitlablab/myapp glab ci run -b feat/ci-pipeline glab ci status --live # Ctrl+C to exit
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.
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).
.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]}.
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
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
Official docs
- Get started with GitLab CI/CD
- CI/CD pipelines
- Runners
- Runner advanced configuration (check_interval, long polling)
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.
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.
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.
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.
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.
Module 2 · .gitlab-ci.yml syntax: stages, jobs and needs (DAG)
- Write a configuration that includes
stages,default,image,services,variables,script. - Use
extends, hidden jobs (starting with.),!referenceand YAML anchors to reduce repetition. - Use
needsto build a DAG and understand its effect on execution order and artifact downloads; learn to useparallel:matrixfor fan-out.
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.
| Keyword | Purpose | Key points |
|---|---|---|
stages | Defines the stage order | If not defined, the default is .pre, build, test, deploy, .post; if a job does not write stage , it belongs to test |
default | default values for jobs | Can 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) |
script | Required; 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_script | Cleanup commands | run in a separate shell, even if the job fails or is cancelled, and cannot see script variables exported in it. |
image / services | Job container image / sidecar containers | Only 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 |
needs | Declare job dependencies and skip the stage wait | Up to 50 (GitLab.com); can depend on jobs in the same stage; needs: [] means the job starts immediately after the pipeline is created. |
extends | Inherit from other jobs (including hidden jobs) | Hashes are deep-merged, arrays are replaced as a whole; up to 11 levels of nesting |
parallel / parallel:matrix | Parallel copies / matrix fan-out | parallel Values 1–200; matrix combinations must not exceed 200 |
allow_failure,retry,timeout,interruptible | Failure tolerance, automatic retry (max 0–2), timeout, and whether it can be cancelled when a new commit is pushed | retry: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
- Execution order: a job only waits for
needs(and their dependencies), instead of waiting for the whole previous stage. - Artifact downloads: jobs with
needsonly downloadneedsartifacts of the jobs inneeds:artifacts(default true); jobs withoutneedsdownload artifacts from all earlier stages by default (can be limited withdependencies).
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
| GitLab | GitHub Actions | Azure Pipelines | Jenkins | |
|---|---|---|---|---|
| Dependency relationships | needs: [job] | needs: job | dependsOn | stage order + parallel block |
| Template inheritance | extends,!reference, anchors | reusable workflows, composite Actions | template Parameterization | shared library functions |
| Matrix | parallel:matrix | strategy.matrix | strategy: matrix | matrix directive |
| service containers | services | services | services (container resources) | plugins / hand-written docker run |
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
Inheritance and reuse: extends, !reference, default
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
| Syntax | Purpose | Notes |
|---|---|---|
needs: [lint] | Only wait for lint | Also download only lint's artifacts |
needs: [] | Start immediately | Wait for no job and download no artifacts |
needs: [{job: build, artifacts: false}] | Wait but do not download artifacts | Reduces download time |
needs: [{job: docs, optional: true}] | Depend on an optional job | No error when docs is excluded by rules |
parallel: {matrix: [{PY: ["3.12","3.13"]}]} | Matrix fan-out | job name will include [3.12] and similar suffixes |
services: [{name: redis:8, alias: cache}] | Sidecar container | reach it via an alias in the job cache access |
retry: {max: 2, when: [runner_system_failure]} | Retry only infrastructure errors | Do not hide flaky tests |
interruptible: true | Can be cancelled automatically when a new commit is pushed | Use 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)
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).
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
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 hiCase 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).
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]
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
Official docs
- CI/CD YAML syntax reference
- Make jobs start earlier with needs
- Optimize GitLab CI/CD configuration files (extends, !reference, anchors)
- Services
Video storyboard script (about 90 seconds)
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.
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.
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”.
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.
Module 3 · rules, workflow and pipeline types (branch / MR / merged result)
- Write
rules:if,rules:changes(includingcompare_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:rulesto avoid “two pipelines per push”, and useworkflow:auto_cancelto cancel outdated pipelines.
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.
| Clause | What it checks | Example |
|---|---|---|
if | Variable expression: ==,!=,=~ (regex),!~,&&,||, parentheses; an undefined variable is treated as null | $CI_COMMIT_BRANCH == $CI_DEFAULT_BRANCH |
changes | Whether the files changed in this push match (up to 50 patterns per clause) | changes: {paths: ["**/*.py"], compare_to: refs/heads/main} |
exists | Whether a file exists in the repository | exists: [Dockerfile] |
when | How the job joins after a match | on_success (default),manual,delayed,always,never |
How: evaluation rules (must memorize)
- Check rules in order; the first matching rule takes effect; the rest are not checked.
- The
whenof the matching rule isnever→ the job is not added; any other value (or not written) → the job is added and uses that rule's attributes. - If no rule matches → the job is not added to the pipeline.
- The
when: manualin rules defaults toallow_failure: false(it blocks later stages and “pipeline must succeed”); when not written in rules,when: manualdefaults toallow_failure: true. changescomparison 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),changesalways evaluates to true, unlesscompare_tois 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
| Type | When it is created | CI_PIPELINE_SOURCE | Code under test | Level |
|---|---|---|---|---|
| Branch pipeline | Push to a branch | push | Latest commit on the branch | Free |
| Tag pipeline | Push a tag | push (CI_COMMIT_TAG has a value) | Commit the tag points to | Free |
| MR pipeline | Created / updated MR, and the configuration has rules for MRs | merge_request_event,CI_MERGE_REQUEST_EVENT_TYPE=detached | Latest commit on the source branch | Free |
| Merged result pipeline | Same as above, with Enable merged results pipelines turned on in Settings → Merge requests | merge_request_event,merged_result | Source and target branches'temporary merge commit (falls back to a regular MR pipeline on conflict) | Premium / Ultimate |
| Merge train | MR joins the merge train | merge_request_event,merge_train | target branch + all earlier MRs in the queue + this MR | Premium / Ultimate |
| Other | Scheduled, manual, API, trigger token, parent-child / multi-project | schedule,web,api,trigger,parent_pipeline,pipeline | Specified ref | Free |
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/exceptis legacy syntax, no longer actively developed, and cannot be mixed in the same job withrules— new configurations should always userules.
Comparison with similar technologies
| GitLab | GitHub Actions | Azure Pipelines | Jenkins | |
|---|---|---|---|---|
| Trigger conditions | workflow:rules + CI_PIPELINE_SOURCE | on: push / pull_request | trigger / pr | Multibranch scan + webhook |
| Job conditions | rules | if: | condition: | when { } |
| Tests the merged code | Merged result pipelines (Premium) | pull_request Checks out the merge commit by default | PR builds use the merge commit by default | Merge strategy of the branch source plugin |
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
Which code the MR pipeline tests
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
| Requirement | rules |
|---|---|
| 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 rule | variables: {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)
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.
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.
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.
CI_MERGE_REQUEST_EVENT_TYPE becomes merged_result. The Free tier skips this step.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.
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_BRANCH2. List the 3 most recent MR pipelines.
glab ci list --source merge_request_event --per-page 3
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:
Official docs
- Specify when jobs run with rules (includes the full CI_PIPELINE_SOURCE table)
- workflow keyword
- Merge request pipelines
- Merged results pipelines
Video storyboard script (about 90 seconds)
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.
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.
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.
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.
Module 4 · variables, protected variables and CI/CD settings
- 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).
What: where variables come from
| Source | Where it is defined | Example |
|---|---|---|
| Predefined variables | Injected automatically by GitLab | CI_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:variables | PIP_DISABLE_PIP_VERSION_CHECK: "1" |
| project / group / instance variables | Settings → CI/CD → Variables (projects need Maintainer, groups need Owner, instances need an administrator) | REGISTRY_PASSWORD |
| Pipeline variables | Passed in by manual runs, the API, trigger tokens, and scheduled runs | glab ci run --variables KEY:VALUE |
| dotenv report | upstream job artifacts:reports:dotenv produces | IMAGE_DIGEST=sha256:… |
How: precedence (highest to lowest, official order)
- Variables in pipeline execution policies / scan execution policies
- Manual job variables (filled in when a manual job is run)
- Pipeline variables (manual runs, API, triggers, scheduled runs)
- Project variables
- Group variables (closer subgroups take precedence)
- Instance variables
- Variables from
dependencies/needsjob's dotenv report variables - YAML variables:
rules:variables> jobvariables>workflow:rules:variables> top levelvariables - Deployment variables
- Predefined variables (of which
CI_ENVIRONMENT_ID,CI_ENVIRONMENT_SLUG,CI_ENVIRONMENT_URL, andCI_PAGES_URLcannot 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
| Option | Effect | Does not protect against |
|---|---|---|
| Protect variable | Injected only into pipelines running on protected branches / protected tags | anyone 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 name | echo $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 creation | Same as Masked; the job can still read it |
| File type | The value is written to a temporary file; the environment variable holds the file path | Scripts read the cat file; but env/printenv does not print the contents directly. |
| Expand variable reference | References 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 scope | Injected 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
| GitLab | GitHub Actions | Azure Pipelines | Jenkins | |
|---|---|---|---|---|
| Secret storage | CI/CD variables (Masked / Protected) | Secrets (automatically masked) | Secure variables / variable groups + Key Vault | Credentials plugin |
| Restrict by branch | Protect variable | Environments + protection rules | Environment approval / branch control checks | Folder / credential scope |
| Short-lived cloud credentials | id_tokens (Lessons 3/4) | permissions: id-token: write | Workload identity federation service connection | Plugin implementation |
kubectl --kubeconfig "$KUBECONFIG_FILE" to read it.Variable merging: ten layers of sources; higher layers override lower ones
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
| Command | Purpose | Key arguments |
|---|---|---|
glab variable set KEY -v VALUE | Create / update a project variable | -m masked,-p protected,--hidden,-t file,-s production,-r raw (no expansion),-g group |
glab variable list | List variables (hidden variables do not show their values) | -g |
glab variable get KEY | Read a value | Requires Maintainer |
glab variable delete KEY | Delete | -s Specify the scope |
glab ci run --variables K:V | Run with pipeline variables | Restricted 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
| Variable | Example value | Purpose |
|---|---|---|
CI_COMMIT_SHORT_SHA | 8f3c2a1b | Image tag |
CI_COMMIT_REF_SLUG | feature-login | URL / branch name safe for image tags |
CI_REGISTRY_IMAGE | registry.gitlab.com/mygroup-lab/myapp | Push an image (only available when the Container Registry is enabled) |
CI_REGISTRY_USER / CI_REGISTRY_PASSWORD | Job-specific credential | docker login $CI_REGISTRY |
CI_JOB_TOKEN | Valid while the job runs | Call some APIs, pull permitted private projects / packages |
CI_COMMIT_REF_PROTECTED | true | Determine whether the ref is protected |
Lab 4: verify protected variables and masking (about 6 minutes)
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']
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
$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]
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.
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)"
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
Official docs
- GitLab CI/CD variables (precedence, masking, hidden, protected)
- Predefined CI/CD variables reference
- Using external secrets in CI
- CI/CD job token
Video storyboard script (about 90 seconds)
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.
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.
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.
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.
Module 5 · Runners: GitLab-hosted, self-managed and executors
- 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 rungitlab-runner register --token) to run a container in Dockergitlab-runner, with tagslab-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.
What: GitLab-hosted Runners (GitLab.com)
| Linux x86-64 machine types | Tags | vCPU / memory / storage | Tier |
|---|---|---|---|
| Small (default) | saas-linux-small-amd64 | 2 / 8 GB / 30 GB | All |
| Medium | saas-linux-medium-amd64 | 4 / 16 GB / 50 GB | All |
| Large / XLarge / 2XLarge | saas-linux-large-amd64 etc. | 8–32 vCPU | Premium / Ultimate |
| Arm64 Small | saas-linux-small-arm64 | 2 / 8 GB / 30 GB | All (Medium and above require Premium) |
- Untagged jobs run on Small Linux x86-64; If
imageis not written, the default isruby: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
| Scope | Who can create it | Who can use it |
|---|---|---|
| Instance Runner | Self-managed instance administrators (on GitLab.com, this is the hosted Runner) | All projects in the instance (projects can opt out) |
| Group Runner | Group Owner | All projects in the group and its subgroups |
| Project Runner | Project Maintainer | Specified 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)
- 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 onePOST /user/runners(the token needs thecreate_runnerscope). - On the Runner host, run
gitlab-runner register --url https://gitlab.com --token glrt-… --executor docker …, and the token is written toconfig.toml. - 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
| Executor | Status (official) | Isolation | Suited to |
|---|---|---|---|
| Docker | Active | One container per job | The default choice; supports image/services |
| Docker Autoscaler | Active | Creates cloud VMs on demand, then runs containers on them | Elastic scaling (replaces Docker Machine) |
| Instance | Active | One on-demand VM per job, exclusive | Jobs that need a full VM |
| Kubernetes | Active | One Pod per job | Existing K8s platform (Lesson 7) |
| Shell | Maintenance mode | No isolation; runs directly on the host | Special hardware, minimal scenarios |
| SSH / VirtualBox / Parallels / Custom | Maintenance mode | Depends on implementation | Legacy or custom environments |
| Docker Machine | Deprecated | — | 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 Runner | GitHub Actions Runner | Azure Pipelines Agent | Jenkins Agent | |
|---|---|---|---|---|
| Hosted | GitLab-hosted Runner | GitHub-hosted runners | Microsoft-hosted agents | No official hosted option |
| Registration credential | glrt- Authentication token | Registration token (short-lived) | PAT / agent pool | Node secret (JNLP) |
| How to choose | tags | runs-on Tags | pool + demands | agent { label } |
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)
Matching conditions for jobs and Runners
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
| Command | Purpose | Notes |
|---|---|---|
gitlab-runner register --non-interactive --url … --token glrt-… --executor docker --docker-image … | Register with an authentication token | tags and other settings are set in the UI |
gitlab-runner verify | Check whether the token is valid | --delete Delete invalid entries |
gitlab-runner list | List the Runners in config.toml | |
gitlab-runner unregister --name … | Unregister | can also be deleted in the UI |
gitlab-runner run | Run 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- token | The 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).
~/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: …
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.
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 = truesudo sed -i 's/^concurrent = .*/concurrent = 2/' ~/gitlablab/runner/config.toml docker logs --tail 5 gitlab-runner
Configuration loaded builds=0 max_builds=2
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.
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).
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
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
Official docs
- Registering runners
- Run GitLab Runner in a container
- Executors
- Hosted runners on Linux
- Compute minutes
- Manage runners (scope)
Video storyboard script (about 90 seconds)
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.
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.
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.
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.
Module 6 · cache, artifacts and dependency passing
- Explain how cache and artifacts differ in storage location, lifecycle, reliability and purpose.
- Design pip dependency caching with
cache:key:files,fallback_keys, andpolicy; understand cache isolation for protected branches. - Pass results between jobs using
artifacts(paths,expire_in,when,reports:junit,reports:dotenv), and control downloads withneeds/dependencies.
What: the essential difference between the two
| cache | artifacts | |
|---|---|---|
| Purpose | Dependencies 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 stored | Stored 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) |
| Reliability | Not guaranteed to exist: changing Runners, the cache being cleaned up, or a changed key all cause a miss | Guaranteed: later jobs can always download them (while not expired) |
| Lifecycle | Reused across pipelines until overwritten or cleaned up | Expires 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 |
| Scope | All 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.) |
| Default | No cache unless defined | Later 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) orkey: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 addkey:prefix. If none of the files exist, the key falls back todefault. There is alsokey: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).policypolicy:pull-push(default),pull(read-only, suited to parallel test jobs),push(write-only).whenpaths:on_success(default),on_failure,always.pathsMust 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
-protectedsuffix 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 example1 week,never; a number without a unit is treated as seconds.whenwhen:on_success(default),on_failure(saves debugging material only on failure),always(timed-out jobs do not upload).reportsReports:junit(show test results in the MR),coverage_report(show coverage in the MR diff),dotenv(turnsKEY=VALUEfiles 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
needsonly download the artifacts of the jobs they need. When needs is not used,dependencies: [job]can limit which ones are downloaded, anddependencies: []downloads no artifacts at all.
When: put it in cache or artifacts?
| Content | Where to put it | Reason |
|---|---|---|
| pip / npm downloaded packages | cache | If lost, they can be re-downloaded; it is just slower |
Build outputs dist/, wheels | artifacts | Later deployment must get the same copy |
| Test reports report.xml, coverage.xml | artifacts:reports | Displayed in the MR |
.venv Virtual environments | Use with caution: a cache | is 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 layers | Container Registry (BuildKit cache-to / cache-from) | Not suited to the CI cache |
Comparison with similar technologies
| GitLab | GitHub Actions | Azure Pipelines | Jenkins | |
|---|---|---|---|---|
| Dependency cache | cache (Runner-local or distributed) | actions/cache (GitHub storage) | Cache@2 Task | Workspace retention / plugin |
| Result passing | artifacts + needs | upload/download-artifact | Pipeline Artifacts | stash/unstash,archiveArtifacts |
| Test reports | reports:junit | Third-party Action | PublishTestResults | junit Steps |
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
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
| Action | Method |
|---|---|
| Clear Runner cache | Build → 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 artifacts | glab job artifact main "unit-test: [3.13]" |
| Browse / delete artifacts | Build → Artifacts; or “Browse / Download / Delete” on the right of the job page |
| Download via the API | glab 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)
echo "pytest-cov>=6" >> requirements-dev.txt
.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).
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"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”.
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: pull2. Download the artifacts of the latest unit-test job on the main branch.
glab job artifact main "unit-test: [3.13]"
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
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)
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.
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.
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.
Visual: two rows of lockers labelled protected and non_protected.
Narration: protected branches use separate caches by default, to prevent poisoning.
Module 7 · include, templates and an introduction to CI/CD components
- 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:inputsand use$[[ inputs.x ]]interpolation; reference official components from the CI/CD Catalog and pin their versions.
What: the five kinds of include
| Type | Syntax | Source and version | Suited to |
|---|---|---|---|
local | include: ci/python.yml or - local: ci/python.yml | same repository, same commit | splitting 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 HEAD | sharing templates within a team |
remote | - remote: https://…/ci.yml | public HTTP(S) URL; authentication not supported; integrity can verify the SHA256 | use with caution |
template | - template: Jobs/Secret-Detection.gitlab-ci.yml | built-in GitLab templates; they change with GitLab versions | traditional access to official features |
component | - component: $CI_SERVER_FQDN/components/secret-detection/secret-detection@2.4.0 | published 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”)
- Includes are merged in the order they are written. If an included file has its own includes,the nested ones are merged first (recursively).
- When parameters overlap,the file merged later takes precedence.
- After all includes are merged,the main file
.gitlab-ci.ymlis merged on top; the main file has the highest precedence. - Deep merge: if both sides are hashes, merge recursively; otherwise (including arrays, such as
scriptandrules) the latter replaces the former as a whole. - 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>.ymlor<name>/template.ymlis a component, and it needsREADME.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;
~latestsome semantic versions (2means the latest 2.*.*,2.4means 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
releasekeyword in CI; after that it appears in the catalog. Official components live in thegitlab.com/componentsgroup (for examplesast,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/componentscomponents, or templates recommended by the docs. remote: only from trusted sources, and pair it withintegrity.
Comparison with similar technologies
| GitLab | GitHub Actions | Azure Pipelines | Jenkins | |
|---|---|---|---|---|
| Reuse unit | CI/CD components, include | Action, reusable workflows | YAML templates (template: + parameters) | Shared Library |
| parameters | spec:inputs | inputs | parameters | function parameters |
| catalog | CI/CD Catalog | Marketplace | — (the extension marketplace is for tasks) | plugin hub |
| version pinning | @1.2.3 / @SHA | @v4 / @SHA | ref resources | @Library('x@tag') |
~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
Component project structure
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
| Action | Method |
|---|---|
| View the merged result | Build → Pipeline editor → “Full configuration” |
| Validate a configuration that contains includes | glab ci lint (server-side expansion) |
| Browse components | Search or Go to → Explore → CI/CD Catalog; or https://gitlab.com/explore/catalog |
| view the official component versions | glab 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)
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.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.
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
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.
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: test2. Include a review configuration file only in MR pipelines.
include:
- local: ci/review.yml
rules:
- if: $CI_PIPELINE_SOURCE == "merge_request_event"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
Official docs
- Use CI/CD configuration from other files (includes merge rules)
- CI/CD components
- components/secret-detection (official component)
- CI/CD Catalog
Video storyboard script (about 90 seconds)
Visual: five colour-coded YAML cards (local, project, remote, template, component) fly in.
Narration: include can assemble configuration from five kinds of sources.
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.
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.
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.
Module 8 · CI readiness review and common failures
- 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_TRACEexposes variables), and be able to reproduce and fix 4 typical kinds of failure.
What: the CI readiness review checklist (10 items)
| # | Dimension | Standard | Module |
|---|---|---|---|
| 1 | Reproducible | each job explicitly specifies image (pinned to a major version or above), without relying on the hosted Runner's default ruby:3.1 | M2, M5 |
| 2 | Triggers | workflow:rules keep only MR pipelines plus default-branch / tag pipelines; no duplicate pipelines | M3 |
| 3 | Gate | main protected, with “pipeline must succeed” on for MRs; lint and tests run in MRs | M3, Lesson 1 |
| 4 | Speed | MR pipelines under 10 minutes; use needs to shorten the critical path interruptible + auto_cancel | M2, M3 |
| 5 | Cache | dependency caching uses key:files; build results use artifacts, not cache | M6 |
| 6 | Visibility | JUnit and coverage reports go into the MR; save debugging artifacts on failure (when: on_failure) | M6 |
| 7 | Secrets | no plaintext secrets; deployment credentials are Protected + Masked (Hidden if possible), with a plan to migrate to OIDC | M4, Lessons 3/4 |
| 8 | Runner | Jobs use tags to declare placement explicitly; privileged or production-capable Runners are set to Protected and not shared | M5 |
| 9 | Reuse | shared configuration is pinned to versions via components / include; no ~latest, and no unvalidated remote includes | M7 |
| 10 | Reliability | retry retry only for infrastructure failures; reasonable timeout; no tests that use allow_failure: true to hide failures | M1, M2 |
How: locate a failure by lifecycle step
| Lifecycle step | Typical symptom | Where to look | Typical cause |
|---|---|---|---|
| 2 Read / expand configuration | Pipeline fails immediately, marked “yaml invalid” | Pipeline editor,glab ci lint | spelling, indentation, include paths, inputs |
| 3–4 Rules | No pipeline / missing job / one extra pipeline | glab ci lint --dry-run --include-jobs, pipeline source | first match,changes always true, needs referencing an excluded job |
| 5–6 Queueing and claiming | Job stays pending / stuck for a long time | job page notice,queued_duration, Runner list | tags, protected Runner, Runner offline, compute minutes used up,concurrent |
| 7 Execution environment | image pull failure, services unreachable, runner system failure | the “Preparing environment” section of the log | image name / permissions, services aliases, dind privileges, disk full |
| 7 Script | ERROR: Job failed: exit code 1 | output before the failing line | test failure, missing dependency, empty variable (protected variable) |
| 8 Cache / artifacts | files missing, upload failure | “Saving cache / Uploading artifacts” section | path outside the project, needs not including the job, exceeds size |
| 9 Status | MR cannot be merged / status not updated | MR widget, merge checks | no 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
| GitLab | GitHub Actions | Azure Pipelines | Jenkins | |
|---|---|---|---|---|
| Syntax validation | CI Lint / pipeline editor / glab ci lint | actionlint (third-party) | Editor validation / “Validate” | Declarative Linter |
| Debug logs | CI_DEBUG_TRACE | ACTIONS_STEP_DEBUG | system.debug | sh -x / log level |
| Retry | UI / glab ci retry / retry: | Re-run jobs | Rerun failed jobs | Replay / retry() |
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
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
| Command | Purpose |
|---|---|
glab ci lint --dry-run --ref BRANCH --include-jobs | Configuration and rules layer: whether pipelines are created and which jobs exist |
glab ci list --status failed --per-page 5 | Recent failed pipelines |
glab ci trace JOB -b BRANCH | View job logs |
glab ci retry JOB | Retry 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 verify | Self-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
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.
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.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.
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).
glab mr close feature/break-ci git switch feat/ci-pipeline && git branch -D feature/break-ci && git push origin --delete feature/break-ci
~/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.
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.
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
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
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)
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.
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.
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.
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.
Command cheat sheet
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: trueglab ci lint [--dry-run --ref B --include-jobs] | Validate / simulate |
glab ci status [--live|--wait] | Current branch status |
glab ci view | Interactive 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 cancel | Retry / 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/NAME | Component versions |
| 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.
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 | artifacts | |
|---|---|---|
| Storage | Runner local / distributed | GitLab |
| Reliable | No | Yes |
| Default lifetime | until overwritten / cleaned up (hosted Runner caches are deleted after 14 days without updates) | 30 days (GitLab.com) |
| Purpose | Dependency downloads | Build results, reports, dotenv |
Policy variables → manual job → pipeline variables → project → group → instance → dotenv → YAML (rules > job > workflow > top level) → deployment → predefined
Protection optionsProtected: 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
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
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
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.
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.
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.
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).
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']
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.
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.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
Versions and releases
| Fact | Value | Source | Verified on |
|---|---|---|---|
| Latest GitLab minor version | 19.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-ee | 2026-11-16 |
| Latest GitLab Runner version | v19.5.3 (2026-11-05) | gitlab-runner CHANGELOG; Docker Hub tag gitlab/gitlab-runner:v19.5.3 | 2026-11-16 |
| Latest glab version | v1.130.0 (2026-11-10) | gitlab-org/cli releases | 2026-11-16 |
| GitLab Secrets Manager | GA in 19.5; Premium / Ultimate, add-on | 19.5 release notes | 2026-11-16 |
| Official component versions | secret-detection 2.4.0; sast 3.5.0 | gitlab.com/components | 2026-11-16 |
CI/CD keywords and behavior
| Topic | Facts used in this lesson | Source |
|---|---|---|
| Global keywords, default, needs, rules, parallel, retry, cache, artifacts | needs ≤ 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 unspecified | CI/CD YAML syntax reference |
| workflow | when in workflow:rules can only be always / never; values of auto_cancel:on_new_commit; official de-duplication rules | workflow |
| Pipeline sources and MR types | full CI_PIPELINE_SOURCE table; CI_MERGE_REQUEST_EVENT_TYPE = detached / merged_result / merge_train | Job rules,Predefined variables |
| merged result pipelines / merge trains | Premium / Ultimate; MR pipelines must be configured, otherwise the MR may get stuck | Merged results pipelines,Merge trains |
| Variables | ten-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_allowed | CI/CD variables,MR pipelines |
| Runner registration | glrt- 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.2 | Registering runners; gitlab-runner source code commands/register.go |
| Runner configuration and polling | check_interval default 3 seconds; Workhorse long polling default 50 seconds; request_concurrency default 1; pull_policy default always | Advanced configuration |
| Executor status | Docker, Docker Autoscaler, Instance, Kubernetes active; Shell, SSH, VirtualBox, Parallels, Custom in maintenance mode; Docker Machine deprecated | Executors |
| Hosted Runners | machine types and tags; untagged uses small; default image ruby:3.1; GCS distributed cache 14 days, 5 GB each; temporary VM | Hosted runners on Linux,Hosted runners |
| Compute minutes and limits | Free 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 verification | email / phone / credit card verification required based on risk; cards are not charged or stored | Identity verification |
| Cache and artifacts | protected cache suffix; clearing the cache requires Developer; artifacts default to 30 days | Caching,Job artifacts |
| include and components | 150 includes, 30 seconds; merge order; component format, version priority, ~latest, 100 components per project (18.5), Catalog publishing requirements, GA in 17.0 | Includes,CI/CD components |
| glab commands and arguments | ci lint/status/list/trace/run/retry/view, variable set, job artifact, repo create, release list | glab docs/source |
| Runner API | POST /user/runners,runner_type,tag_list,run_untagged, the token needs the create_runner scope | Users 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:
- GitLab CI CD Tutorial for Beginners [Crash Course] — TechWorld with Nana
- GitLab CI CD Pipeline Tutorial | Introduction | 2022 — Moss
- Gitlab CI pipeline tutorial for beginners — Valentin Despa
- DevOps with GitLab CI Course - Build Pipelines and Deploy to AWS — freeCodeCamp.org
- Parent-Child Pipelines feature demo — GitLab Unfiltered
- Managing the Complex Configuration Data Management Monster Using GitLab — GitLab Unfiltered
- GitLab CI CD automation (Docker, Kubernetes, Terraform, and more…) — Christian Lempa
- Talk: Efficient DevSecOps workflows with reusable CI/CD components — GitLab Unfiltered
- NEW GitLab CI CD components explained — Christian Lempa
- [Demo] Use of predefined project variables in `include` section of .gitlab-ci.yml — GitLab Unfiltered
- Learn GitLab in 3 Hours | GitLab Complete Tutorial For Beginners — TestMu AI (Formerly LambdaTest)
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.