CI/CD Exercises
Each exercise is a small piece of pipeline logic written as a pure function, with the calls already in place. Run the starter first: it prints placeholder answers, which shows what the calls expect. Complete the code marked TODO until the output matches the expected output, then compare with the solution. The last exercise is a real GitLab pipeline with a bug to fix.
Exercise 1: Run jobs in waves
Topics: Anatomy of a Pipeline, Job Graphs & Conditions
Given jobs and their needs, return the waves a CI system would run: wave 1 holds every job with no dependencies, each later wave the jobs whose needs are all done, names sorted within a wave. If some jobs can never run, raise ValueError("cycle between: a, b, c") naming them (sorted).
JOBS = {
"lint": [], "unit": [], "build": ["lint", "unit"], "scan": ["build"],
"e2e": ["build"], "push": ["scan", "e2e"], "deploy": ["push"],
}
def order(jobs):
# TODO: repeatedly collect the jobs whose needs are all done
return [sorted(jobs)]
for wave, jobs in enumerate(order(JOBS), start=1):
print(f"wave {wave}: {' '.join(jobs)}")
try:
order({"a": ["c"], "b": ["a"], "c": ["b"], "d": []})
except ValueError as e:
print(e)wave 1: build deploy e2e lint push scan unit
Expected output:
wave 1: lint unit
wave 2: build
wave 3: e2e scan
wave 4: push
wave 5: deploy
cycle between: a, b, cShow solution
def order(jobs):
done, result = set(), []
while len(done) < len(jobs):
ready = sorted(j for j in jobs if j not in done and all(n in done for n in jobs[j]))
if not ready:
raise ValueError("cycle between: " + ", ".join(sorted(set(jobs) - done)))
result.append(ready)
done.update(ready)
return resultd in the second graph would run, but a, b and c wait for each other forever. GitHub and GitLab reject such files when they load them.
Exercise 2: Rolling update bounds
Topics: Rolling Deployments
Kubernetes turns percentage maxSurge and maxUnavailable into pod counts: surge rounds up, unavailable rounds down. Return the minimum number of ready pods and the maximum number of pods during a rollout.
import math
def bounds(replicas, max_surge_pct, max_unavailable_pct):
# TODO: convert the percentages and return (min_ready, max_total)
return (replicas, replicas)
for args in [(4, 25, 25), (10, 25, 25), (3, 50, 0), (7, 10, 10)]:
print(args, "->", bounds(*args))(4, 25, 25) -> (4, 4)
(10, 25, 25) -> (10, 10)
(3, 50, 0) -> (3, 3)
(7, 10, 10) -> (7, 7)
Expected output:
(4, 25, 25) -> (3, 5)
(10, 25, 25) -> (8, 13)
(3, 50, 0) -> (3, 5)
(7, 10, 10) -> (7, 8)Show solution
def bounds(replicas, max_surge_pct, max_unavailable_pct):
surge = math.ceil(replicas * max_surge_pct / 100)
unavailable = math.floor(replicas * max_unavailable_pct / 100)
return (replicas - unavailable, replicas + surge)The last case shows the rounding at work: 10 % of 7 is 0.7, so one extra pod may start but none may be unavailable.
Exercise 3: The canary decision
Topics: Canary Releases & Automated Analysis
Return "extend" if the canary has fewer than min_requests requests, "fail" if its error rate exceeds the stable rate by more than max_diff, otherwise "pass". Each side is (requests, errors); a side with 0 requests has an error rate of 0.
def decide(stable, canary, min_requests=200, max_diff=0.01):
# TODO
return "pass"
cases = [((9500, 95), (120, 3)), ((9500, 95), (500, 6)), ((9500, 95), (500, 12)),
((0, 0), (300, 2)), ((4000, 200), (400, 24))]
for stable, canary in cases:
print(f"stable {stable} canary {canary} -> {decide(stable, canary)}")stable (9500, 95) canary (120, 3) -> pass
stable (9500, 95) canary (500, 6) -> pass
stable (9500, 95) canary (500, 12) -> pass
stable (0, 0) canary (300, 2) -> pass
stable (4000, 200) canary (400, 24) -> pass
Expected output:
stable (9500, 95) canary (120, 3) -> extend
stable (9500, 95) canary (500, 6) -> pass
stable (9500, 95) canary (500, 12) -> fail
stable (0, 0) canary (300, 2) -> pass
stable (4000, 200) canary (400, 24) -> passShow solution
def decide(stable, canary, min_requests=200, max_diff=0.01):
if canary[0] < min_requests:
return "extend"
rate = lambda side: side[1] / side[0] if side[0] else 0.0
return "fail" if rate(canary) - rate(stable) > max_diff else "pass"The last case passes although the canary has 6 % errors: stable has 5 %, so the problem is shared (a downstream outage), not the canary's.
Exercise 4: A vulnerability gate with expiring exceptions
Topics: Container Scanning as a CI Gate, Shift Left
Return the IDs that block a release on today: a finding blocks if it is in CISA's KEV list (kev), or if its severity is at least threshold and a fix exists. Findings in ignores don't block while their expiry date is today or later.
from datetime import date
FINDINGS = [
{"id": "CVE-2026-1001", "severity": "CRITICAL", "fixed": True, "kev": False},
{"id": "CVE-2026-1002", "severity": "HIGH", "fixed": False, "kev": False},
{"id": "CVE-2026-1003", "severity": "HIGH", "fixed": True, "kev": False},
{"id": "CVE-2026-1004", "severity": "MEDIUM", "fixed": True, "kev": True},
{"id": "CVE-2026-1005", "severity": "LOW", "fixed": True, "kev": False},
]
IGNORES = {"CVE-2026-1001": date(2026, 12, 31), "CVE-2026-1003": date(2026, 3, 1)}
RANK = {"LOW": 1, "MEDIUM": 2, "HIGH": 3, "CRITICAL": 4}
def gate(findings, ignores, today, threshold="HIGH"):
# TODO: skip active exceptions; block KEV, and fixable findings at or above the threshold
return []
for today in (date(2026, 2, 1), date(2026, 6, 1), date(2027, 2, 1)):
b = gate(FINDINGS, IGNORES, today)
print(f"{today}: {'FAIL ' + ', '.join(b) if b else 'pass'}")2026-02-01: pass
2026-06-01: pass
2027-02-01: pass
Expected output:
2026-02-01: FAIL CVE-2026-1004
2026-06-01: FAIL CVE-2026-1003, CVE-2026-1004
2027-02-01: FAIL CVE-2026-1001, CVE-2026-1003, CVE-2026-1004Show solution
def gate(findings, ignores, today, threshold="HIGH"):
blocking = []
for f in findings:
if f["id"] in ignores and ignores[f["id"]] >= today:
continue
if f["kev"] or (RANK[f["severity"]] >= RANK[threshold] and f["fixed"]):
blocking.append(f["id"])
return blockingCVE-2026-1002 never blocks (no fix exists yet; it belongs in the backlog report), and the two exceptions stop protecting the release as soon as they expire.
Exercise 5: A deploy job that runs everywhere
Topics: needs, rules & workflow:rules
This pipeline should create deploy-production only on the default branch, yet the session (on a feature branch) shows it in the list. Find the bug and fix the rules so the job disappears on feature branches and stays on main.
mkdir shop && cd shop && git init -q
git commit -q --allow-empty -m "init"
git remote add origin https://gitlab.example.com/acme/shop.git
git update-ref refs/remotes/origin/main HEAD && git remote set-head origin main
cat > .gitlab-ci.yml <<'YML'
stages: [test, deploy]
unit:
stage: test
script: [echo "tests"]
deploy-production:
stage: deploy
rules:
- when: on_success
- if: $CI_COMMIT_BRANCH != $CI_DEFAULT_BRANCH
when: never
script: [echo "deploy"]
YML
git add . && git commit -qm "ci"
git switch -q -c feature/cart
gitlab-ci-local --list 2>&1 | tail -n +3name description stage when allow_failure environment needs
unit test on_success false
deploy-production deploy on_success false
Expected output on feature/cart:
name description stage when allow_failure environment needs
unit test on_success falseShow solution
Rules are evaluated top to bottom and the first match wins. - when: on_success has no condition, so it matches every pipeline and the never rule is never reached. Put the specific rule first, or (clearer) state the positive condition only:
deploy-production:
stage: deploy
rules:
- if: $CI_COMMIT_BRANCH == $CI_DEFAULT_BRANCH
script: [echo "deploy"]With no matching rule, the job is not added on other branches.
Test yourself
In Exercise 5, why did deploy-production appear on the feature branch?
- gitlab-ci-local ignores rules
- The unconditional first rule matched every pipeline, so the
neverrule was never evaluated - CI_DEFAULT_BRANCH was empty
- Manual jobs always appear
In Exercise 4, why doesn't CVE-2026-1002 (HIGH) ever block?
- It is ignored
- No fix exists, and the policy only blocks fixable findings (or KEV entries)
- HIGH is below the threshold
- It's a duplicate