Lesson 4 — Continuous Integration & Quality Gates
Course: DevOps & Platform Engineering (devops) · Group: Data Engineering
Workplace: Northline (illustrative synthetic organisation)
Assumed environment: Ubuntu 22.04 LTS (illustrative); GitHub Actions used as the primary CI example — concepts apply to GitLab CI, Jenkins, Tekton, Buildkite, and others. Specific Action names and versions are illustrative; check the GitHub Actions Marketplace for current stable releases before use.
Status: approved
Learning objectives & deliverable
By the end of this lesson you will be able to:
- Explain what triggers a CI pipeline and how trigger rules control when jobs run.
- Design a multi-stage pipeline with lint, unit test, security scan, and dependency scan stages.
- Distinguish between artefact caching and artefact storage, and explain when each applies.
- Set and enforce quality gate thresholds (test coverage, vulnerability severity).
- Identify the causes of false-green pipelines and apply corrections.
- Manage pipeline secrets safely using environment-injected variables and least-privilege token scopes.
- Read a pipeline failure and locate the root cause efficiently.
Deliverable: A CI pipeline YAML file for a fictional Northline Python service, implementing the four quality-gate stages described in this lesson, with a code-coverage threshold and a dependency-scan step. Validated by running the pipeline against a provided test repository. Reviewed by teacher.
Prerequisites
| Concept | Where to learn it |
|---|---|
| DevOps delivery lifecycle | Lesson 1 — DevOps & Platform Engineering #devops1 |
| Shell scripting, exit codes, environment variables | Lesson 2 — Linux & Bash #devops2 |
| Branch protection, pull requests, secrets prevention | Lesson 3 — Git Workflows #devops3 |
| Docker basics (image, container, build) | General Docker documentation (not covered in this course) |
Lesson opener
In one line: A CI pipeline is the automated immune system of a codebase — it rejects broken, insecure, or low-quality changes before they reach production.
Why it matters: The protected branch rules from #devops3 require status checks to pass before a PR can merge. Those status checks are satisfied by CI pipeline jobs. A pipeline that always goes green (whether the code is good or not) is worse than no pipeline: it creates false confidence. A pipeline that takes 45 minutes drives engineers to bypass it. This lesson teaches how to design pipelines that are fast, trustworthy, and genuinely protective.
Before this lesson: #devops1 for delivery lifecycle context; #devops2 for shell scripting; #devops3 for branch protection and secrets handling.
Northline's platform team received a security incident report: a dependency in the data-ingestion service had a known critical vulnerability (CVE — illustrative) that had been in production for four months. The vulnerability had been in the upstream package before the team adopted it. No dependency scan existed in the CI pipeline. Adding one retroactively found six more issues across three services. This lesson shows how to build the scans that catch these before code ever reaches production.
1. CI Pipeline Fundamentals
1.1 What a CI pipeline is
A CI pipeline is an automated sequence of jobs that runs in response to a code event (push, pull request, tag). Each job runs in an isolated environment (a container or virtual machine), executes commands, reports a pass/fail status, and produces outputs (logs, artefacts, reports).
The pipeline's job is to answer one question: "Is this change safe to merge and deploy?"
A pipeline cannot prove code is correct. It can prove, to a configurable degree of confidence, that the code meets the team's defined quality standards.
1.2 Pipeline anatomy — GitHub Actions concepts (illustrative)
GitHub Actions organises CI as: Workflow → Jobs → Steps.
| Level | Description |
|---|---|
| Workflow | A YAML file in .github/workflows/. Triggered by events. Contains one or more jobs. |
| Job | A set of steps that runs on a single runner (virtual machine or container). Jobs run in parallel by default. |
| Step | A single shell command or a pre-built Action. Steps within a job run sequentially. |
| Runner | The execution environment. GitHub-hosted runners use Ubuntu 22.04, Windows, or macOS. Self-hosted runners are environment-specific. |
Illustrative assumption: This lesson uses GitHub Actions YAML syntax. The same logical concepts (trigger, job, step, artefact, cache, secret) exist in all CI platforms under different naming conventions.
2. Triggers
Triggers define when a workflow runs. Choosing the right trigger for each pipeline prevents unnecessary work and ensures checks run at the right time.
2.1 Common trigger types (GitHub Actions on:)
on:
# Run on every push to main and release branches
push:
branches:
- main
- 'release/**'
# Run on every PR targeting main
pull_request:
branches:
- main
# Run when a semver tag is pushed (e.g., for release build)
push:
tags:
- 'v[0-9]+.[0-9]+.[0-9]+'
# Run on a schedule (cron syntax; UTC timezone on GitHub Actions)
schedule:
- cron: '0 2 * * 1' # every Monday at 02:00 UTC
# Run manually from the GitHub UI or API
workflow_dispatch:
inputs:
environment:
description: 'Target environment'
required: true
default: 'staging'2.2 Path filters — avoid redundant runs
on:
pull_request:
paths:
- 'src/**'
- 'tests/**'
- 'requirements*.txt'
- '.github/workflows/ci.yml'With path filters, a PR that only changes docs/ does not trigger the full CI pipeline. This reduces runner usage and cost (pricing and runner quotas are environment-dependent).
2.3 Concurrency — preventing queue build-up
concurrency:
group: ci-${{ github.ref }}
cancel-in-progress: trueThis cancels any running pipeline for the same branch when a new push arrives. Prevents a queue of stale runs accumulating when an engineer pushes several commits in rapid succession.
3. Pipeline Stages — The Four Quality Gates
Northline's standard CI pipeline for Python services has four sequential quality-gate stages. Each stage is a separate job; each must pass before the next runs.
┌──────────┐ ┌──────────┐ ┌──────────────┐ ┌──────────────────┐
│ 1. Lint │───►│ 2. Test │───►│ 3. Dep Scan │───►│ 4. Container │
│ │ │ │ │ │ │ Build + Scan │
└──────────┘ └──────────┘ └──────────────┘ └──────────────────┘3.1 Stage 1 — Lint and Static Analysis
Lint catches style violations, potential bugs, and formatting issues before the test runner is even invoked. It is the cheapest check and should run first.
# .github/workflows/ci.yml — illustrative; pin all Action versions before use
jobs:
lint:
runs-on: ubuntu-22.04
steps:
- uses: actions/checkout@v4
- name: Set up Python
uses: actions/setup-python@v5
with:
python-version: '3.11' # pin Python version; adjust as needed
- name: Install lint dependencies
run: pip install ruff==0.3.0 # pin version
- name: Lint with ruff
run: ruff check src/ tests/
- name: Format check
run: ruff format --check src/ tests/What ruff catches (illustrative): Unused imports, undefined variables, line length violations, dangerous patterns (exec, bare except), import order. Ruff is one example; Flake8, pylint, and others are alternatives with different rule sets.
Threshold: Lint is a pass/fail gate — any violation fails the job. There is no "warning" mode in production pipelines; warnings that cannot be fixed become ignored noise.
3.2 Stage 2 — Unit Tests with Coverage Threshold
test:
needs: lint # only runs if lint passes
runs-on: ubuntu-22.04
steps:
- uses: actions/checkout@v4
- name: Set up Python
uses: actions/setup-python@v5
with:
python-version: '3.11'
- name: Install dependencies
run: pip install -r requirements.txt -r requirements-dev.txt
- name: Run tests with coverage
run: |
pytest tests/ \
--cov=src \
--cov-report=xml \
--cov-report=term-missing \
--cov-fail-under=80 \
-v
- name: Upload coverage report
uses: actions/upload-artifact@v4
if: always() # upload even if tests fail, so the report is available for diagnosis
with:
name: coverage-report
path: coverage.xml
retention-days: 14Coverage threshold (--cov-fail-under=80): The pipeline fails if overall coverage drops below 80 %. This threshold is illustrative; the right value depends on the team's risk tolerance, the type of service, and historical baseline. Setting it too low (e.g., 10 %) provides no protection; setting it above what is genuinely achievable causes constant failures.
What needs: does: The test job waits for lint to complete successfully before starting. Without needs:, all jobs start in parallel.
3.3 Stage 3 — Dependency Vulnerability Scan
dependency-scan:
needs: test
runs-on: ubuntu-22.04
steps:
- uses: actions/checkout@v4
- name: Set up Python
uses: actions/setup-python@v5
with:
python-version: '3.11'
- name: Install pip-audit
run: pip install pip-audit==2.7.2 # pin version
- name: Scan dependencies
run: |
pip install -r requirements.txt
pip-audit --strict --format=json --output=audit-report.json
# --strict: exit non-zero on any vulnerability
# --format=json: machine-readable output for reporting
- name: Upload audit report
uses: actions/upload-artifact@v4
if: always()
with:
name: dependency-audit
path: audit-report.json
retention-days: 14pip-audit is one illustrative tool for Python dependency scanning. Alternatives include safety, Snyk, and Dependabot alerts. Check current availability, pricing, and feature set for your environment.
Threshold policy: Northline fails the pipeline on any CRITICAL or HIGH severity CVE. MEDIUM vulnerabilities generate a warning artefact and a Jira ticket but do not block the merge (this is a policy decision; more conservative teams block on MEDIUM). Severity levels are defined by the CVE scoring system (CVSS); check current CVSS documentation for definitions.
3.4 Stage 4 — Container Image Build and Security Scan
container-build-scan:
needs: dependency-scan
runs-on: ubuntu-22.04
steps:
- uses: actions/checkout@v4
- name: Build container image
run: |
docker build \
--build-arg GIT_SHA=${{ github.sha }} \
-t stream-processor:${{ github.sha }} \
-f Dockerfile \
.
- name: Scan container image with Trivy
uses: aquasecurity/trivy-action@0.19.0 # pin version; check current releases
with:
image-ref: stream-processor:${{ github.sha }}
format: 'table'
exit-code: '1'
severity: 'CRITICAL,HIGH'
# exit-code 1: fail the pipeline on CRITICAL or HIGH findings
- name: Upload Trivy report
uses: actions/upload-artifact@v4
if: always()
with:
name: trivy-report
path: trivy-results.txt
retention-days: 14Trivy scans the container image layers for OS package vulnerabilities, not just Python dependencies. A Python dependency scan (stage 3) and a container scan (stage 4) together cover different vulnerability surfaces.
Note: Trivy Action versions and configuration options change. Always check the current Aqua Security Trivy documentation before deploying this to production.
4. Artefact Caching
4.1 The problem caching solves
Installing Python dependencies from PyPI on every pipeline run takes 60–180 seconds for a typical data engineering project. With ten engineers each pushing multiple times a day, this adds up to significant CI runner time (and cost, where applicable — pricing is environment-dependent).
Caching stores the installed dependency tree between runs. If requirements.txt has not changed, the cache is restored and pip install is skipped.
4.2 Dependency cache example
- name: Cache pip dependencies
uses: actions/cache@v4
id: pip-cache
with:
path: ~/.cache/pip
# Cache key: invalidates when requirements files change
key: ${{ runner.os }}-pip-${{ hashFiles('requirements*.txt') }}
restore-keys: |
${{ runner.os }}-pip-
- name: Install dependencies
# If cache hit, pip install is significantly faster (only verifies)
run: pip install -r requirements.txt -r requirements-dev.txtCache key design:
hashFiles('requirements*.txt'): the cache is invalidated whenever any requirements file changes.restore-keys: if no exact match, fall back to a partial match (e.g., a cache from the previous day'srequirements.txt). Partial caches still reduce install time.
4.3 Caching vs. artefact storage
| Cache | Artefact | |
|---|---|---|
| Purpose | Speed up repeated steps by reusing unchanged outputs | Preserve job outputs for inspection, download, or use in later jobs/workflows |
| Eviction | Automatic (oldest evicted when quota is reached) | After configured retention period |
| Use between PRs | Yes — cache is shared across branches | Can be scoped to the run |
| Example | ~/.cache/pip, node_modules/, .gradle/caches/ | coverage.xml, audit-report.json, container image layer |
Do not cache build outputs that include secrets or sensitive data. Caches may be accessible to other workflows in the same repository.
5. False-Green Pipelines
A false-green pipeline is one that reports success when the code is not actually safe or correct. It is one of the most dangerous failure modes in CI because it creates trust in a broken system.
5.1 Common causes
| Cause | Mechanism | Symptom | ||||
|---|---|---|---|---|---|---|
| Tests removed to make them pass | Developer deletes test or marks it xfail/skip without justification | Coverage drops but threshold not enforced; no review of skipped tests | ||||
| Coverage threshold too low | --cov-fail-under=10 passes code with minimal tests | 95 % of code paths untested | ||||
| Flaky tests ` | true`-d | `pytest ... | true` silently ignores test failures | Pipeline always green regardless of test outcome | ||
| Hardcoded fixture instead of real logic | Tests assert against hardcoded strings, not computed output | Tests pass even when the logic is completely broken | ||||
| Dependency scan skipped for "legacy" code | An exception list grows unchecked | Known vulnerabilities persist in production | ||||
| Pipeline timeout too short | Jobs that take too long are cancelled and counted as "cancelled" (not "failed") | Platform counts cancelled as non-blocking |
5.2 Detecting false-greens
# Check if any test was skipped in the last run
# In pytest XML output:
grep -c 'status="skipped"' test-results.xml
# Check the actual coverage number (not just pass/fail)
# Read the coverage.xml or the console output artefact
# Review git history for || true patterns in workflow files
git log -p .github/workflows/ | grep '|| true'5.3 Preventing false-greens
- Enforce minimum coverage and increase it gradually as the test suite matures.
- Require justification for skipped tests in PR review: any
pytest.mark.skiporpytest.mark.xfailadded in a PR must have a linked ticket in the reason string. - Never use
|| trueon test steps. If a job must be allowed to fail without blocking merge, use GitHub Actions'continue-on-error: truewith a separate notification step — make the failure visible, not silent. - Audit the pipeline YAML in code review with the same rigour as application code. A pipeline change that adds
|| trueor removes a required check is a security and quality regression. - Validate pipeline logic periodically by intentionally introducing a known bug in a branch and confirming the pipeline catches it.
5.4 continue-on-error vs || true
# BAD — completely silences the failure
- name: Run tests
run: pytest tests/ || true
# BETTER — makes the failure visible in the summary without blocking the pipeline
# (use only when a genuine non-blocking check is needed; document why)
- name: Run optional benchmark
continue-on-error: true
run: pytest tests/benchmarks/
# GOOD — failure is visible, blocks merge, forces fix
- name: Run tests
run: pytest tests/6. Pipeline Secrets and Permissions
6.1 Why secrets in pipelines are high risk
CI pipelines run untrusted code paths (pull request pipelines may be triggered by external contributors). A secret available in a PR pipeline can be exfiltrated by a malicious PR that cats environment variables. GitHub's default behaviour restricts secrets from being available to PRs from forks — verify this setting is active in your repository.
6.2 GitHub Actions secrets (illustrative)
Secrets are stored in the repository settings (or organisation/environment settings) and injected as environment variables at runtime. They are masked in logs — the value is replaced with ***.
jobs:
deploy:
runs-on: ubuntu-22.04
environment: staging # use environment-scoped secrets for sensitive targets
steps:
- name: Deploy to staging
env:
DEPLOY_TOKEN: ${{ secrets.NORTHLINE_DEPLOY_TOKEN }}
DB_URL: ${{ secrets.STAGING_DB_URL }}
run: |
# Secret is available as $DEPLOY_TOKEN in this step only
./scripts/deploy.sh staging
# NEVER echo or print $DEPLOY_TOKENnever print secrets.
echo $DEPLOY_TOKENwill be masked in the log (showing*), but the masking is not 100 % reliable for all secret formats. Treat printing as a prohibited pattern regardless.
6.3 Least-privilege tokens
GitHub Actions generates a GITHUB_TOKEN for each workflow run. Scope it to the minimum permissions needed.
permissions:
contents: read # can read repository content
pull-requests: write # can post PR comments (for coverage reports, scan summaries)
issues: read
# All other permissions: noneDefault permissions (configurable at organisation or repository level) are either "read-all" or "write-all". Set the default to "read-all" at the organisation level and grant additional permissions per workflow explicitly. Check your platform's current documentation for the exact configuration path.
6.4 Secret scanning in CI (complement to pre-commit)
Pre-commit hooks (#devops3) prevent secrets from being committed locally. A CI-level scan provides a second check for secrets that bypassed the pre-commit hook (e.g., a contributor without pre-commit installed).
secret-scan:
runs-on: ubuntu-22.04
steps:
- uses: actions/checkout@v4
with:
fetch-depth: 0 # scan full history, not just the latest commit
- name: Run gitleaks
uses: gitleaks/gitleaks-action@v2 # pin version; check current releases
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}7. Reading a Pipeline Failure
Efficiently diagnosing a CI failure is a skill that saves significant time.
7.1 Failure hierarchy
- Check which job failed in the workflow summary view — not all jobs, just the one with the red ×.
- Expand the failing step within that job — GitHub Actions shows step-level pass/fail.
- Read the last 20 lines of the failing step's output — errors almost always surface at the end.
- Search for the first non-zero exit code — the line immediately before the process exit is usually the error.
- Download artefacts (coverage.xml, audit-report.json) for richer context if the log is insufficient.
7.2 Useful patterns for reading CI logs
# If the pipeline log is downloaded as a text file:
grep -n "ERROR\|FAILED\|error\|exit code" ci_log.txt
grep -n "AssertionError\|ImportError\|ModuleNotFound" ci_log.txt
# pytest failure pattern — find the summary section
grep -A 20 "FAILED\|short test summary" ci_log.txt7.3 Common failure signatures
| Symptom in log | Likely cause |
|---|---|
ModuleNotFoundError: No module named 'X' | Dependency not in requirements.txt; or wrong Python version installed |
No such file or directory: 'coverage.xml' | Tests failed before coverage report was generated; check earlier steps |
permission denied | Script not executable (chmod +x); or step writing to a read-only path |
exit code 137 | Out-of-memory kill (OOM); runner ran out of RAM |
Cache not found for key... | Cache miss — not a failure; first run always misses |
Rate limit exceeded | PyPI or GitHub API rate limit; add retry logic or a cache |
| Scan step fails with no CVEs listed | Wrong image tag; scan ran on empty or wrong artefact |
Complete Pipeline Example — Northline Stream Processor
The following is the complete illustrative pipeline for northline-stream-processor. It integrates all four stages with caching and secrets handling.
# .github/workflows/ci.yml
# Northline stream-processor CI pipeline — illustrative
# Pin all Action versions to specific tags before production use
# Pricing/quota: GitHub-hosted runner minutes are environment-dependent
name: CI
on:
pull_request:
branches: [main]
paths:
- 'src/**'
- 'tests/**'
- 'requirements*.txt'
- 'Dockerfile'
- '.github/workflows/ci.yml'
push:
branches: [main]
concurrency:
group: ci-${{ github.ref }}
cancel-in-progress: true
permissions:
contents: read
pull-requests: write
jobs:
lint:
name: Lint & Format
runs-on: ubuntu-22.04
steps:
- uses: actions/checkout@v4
- uses: actions/setup-python@v5
with:
python-version: '3.11'
- uses: actions/cache@v4
with:
path: ~/.cache/pip
key: lint-${{ hashFiles('requirements-dev.txt') }}
- run: pip install ruff==0.3.0
- run: ruff check src/ tests/
- run: ruff format --check src/ tests/
test:
name: Unit Tests + Coverage
needs: lint
runs-on: ubuntu-22.04
steps:
- uses: actions/checkout@v4
- uses: actions/setup-python@v5
with:
python-version: '3.11'
- uses: actions/cache@v4
with:
path: ~/.cache/pip
key: ${{ runner.os }}-pip-${{ hashFiles('requirements*.txt') }}
restore-keys: ${{ runner.os }}-pip-
- run: pip install -r requirements.txt -r requirements-dev.txt
- name: Run pytest with coverage
run: |
pytest tests/ \
--cov=src \
--cov-report=xml \
--cov-report=term-missing \
--cov-fail-under=80 \
--junitxml=test-results.xml \
-v
- uses: actions/upload-artifact@v4
if: always()
with:
name: test-results
path: |
coverage.xml
test-results.xml
retention-days: 14
dependency-scan:
name: Dependency Vulnerability Scan
needs: test
runs-on: ubuntu-22.04
steps:
- uses: actions/checkout@v4
- uses: actions/setup-python@v5
with:
python-version: '3.11'
- uses: actions/cache@v4
with:
path: ~/.cache/pip
key: ${{ runner.os }}-pip-${{ hashFiles('requirements.txt') }}
restore-keys: ${{ runner.os }}-pip-
- run: pip install pip-audit==2.7.2
- name: Install production dependencies
run: pip install -r requirements.txt
- name: Audit dependencies
run: |
pip-audit --strict --format=json --output=audit-report.json
- uses: actions/upload-artifact@v4
if: always()
with:
name: dependency-audit
path: audit-report.json
retention-days: 14
container-build-scan:
name: Container Build & Trivy Scan
needs: dependency-scan
runs-on: ubuntu-22.04
steps:
- uses: actions/checkout@v4
- name: Build image
run: |
docker build \
--build-arg GIT_SHA=${{ github.sha }} \
-t stream-processor:${{ github.sha }} \
.
- name: Scan with Trivy
uses: aquasecurity/trivy-action@0.19.0
with:
image-ref: stream-processor:${{ github.sha }}
format: 'table'
exit-code: '1'
severity: 'CRITICAL,HIGH'
- name: Secret scan (full history)
uses: gitleaks/gitleaks-action@v2
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}Worked Example A — Diagnosing a Coverage Gate Failure
Symptom: The test job fails with:
FAILED tests/test_dlq.py::test_dlq_retry_limit - AssertionError
...
FAILED tests/test_consumer.py::test_deserialization_error - AssertionError
Coverage failure: total coverage 74% is less than minimum required 80%Diagnosis steps:
- Open the test job artefact:
test-results.xmlandcoverage.xml. - The JUnit XML shows two failing tests and the coverage report shows
src/consumer/router.pyat 12 % coverage. - The developer added
router.pyin this PR but wrote no tests for it.
Correction:
- Write unit tests for
router.pythat bring its coverage to ≥ 80 %. - Fix the two failing assertions (unrelated to coverage — the DLQ retry logic has a bug).
- Push; CI re-runs.
Validation: Next CI run shows all tests pass, coverage is 83 %, no skipped tests.
Prevention: Require a test file to accompany any new source file. This can be enforced by a CODEOWNERS rule requiring a second reviewer for any PR that adds a new module without a corresponding test file.
Worked Example B — Dependency Scan Blocking a Merge
Symptom: The dependency-scan job fails:
{
"vulnerabilities": [
{
"name": "confluent-kafka",
"version": "1.9.0",
"id": "GHSA-xxxx-xxxx-xxxx",
"fix_versions": ["2.3.1"],
"severity": "HIGH"
}
]
}(CVE identifier is illustrative; do not use this ID as a real reference.)
Diagnosis:
- Read the audit report artefact.
- The installed version is
1.9.0;2.3.1is the patched version. - Check
requirements.txt:confluent-kafka==1.9.0(pinned).
Correction:
# 1. Update the pin in requirements.txt
# Change: confluent-kafka==1.9.0
# To: confluent-kafka==2.3.1
# 2. Verify the new version is compatible with the codebase
pip install confluent-kafka==2.3.1
python -m pytest tests/ -x -q
# 3. If tests pass, commit
git add requirements.txt
git commit -m "chore: update confluent-kafka to 2.3.1 to remediate HIGH CVE (NL-2198)"Validation: CI dependency-scan job passes with no findings at HIGH or CRITICAL. Coverage and test jobs were not affected by the library update.
Failure Scenario — Pipeline Always Green Despite Broken Tests
Symptom: Engineers report that the pipeline passes but the service fails on startup in staging.
Investigation:
# Download and inspect the CI log for the test job
grep -n "|| true\|exit 0\|continue-on-error" .github/workflows/ci.ymlFinding: A previous engineer added || true to the pytest step three weeks ago to "unblock a deploy deadline". The test suite had been broken since then and no one noticed because the pipeline showed green.
Root cause analysis:
|| truemasks the non-zero exit code from pytest.- The step always exits 0 regardless of test outcome.
- The coverage report was generated but the pipeline did not fail on
--cov-fail-under=80. - Three breaking changes merged in the intervening weeks.
Correction:
- Remove
|| true. - Run tests locally; fix the three breaking changes (separate PRs, each with clear commit messages).
- Add a pipeline linting check: in the repository's CI workflow, add a step that runs
grep -rn "|| true" .github/workflows/and fails if found.
Prevention: Code-review pipeline YAML changes with the same scrutiny as application code. The CODEOWNERS file should assign @northline-internal/platform-team as required reviewers for all .github/workflows/ files.
Guided Practice
Task: Write and run the ci.yml pipeline for a minimal Northline Python service.
Setup (local test environment — Ubuntu 22.04 LTS or WSL2):
# Create a minimal Python project
mkdir northline-ci-practice && cd northline-ci-practice
git init
git checkout -b main
# Create src and test files
mkdir -p src tests
cat > src/counter.py << 'EOF'
def count_errors(lines):
"""Count lines containing 'ERROR'. Returns int."""
return sum(1 for line in lines if "ERROR" in line)
EOF
cat > tests/test_counter.py << 'EOF'
from src.counter import count_errors
def test_count_errors_basic():
lines = ["INFO ok", "ERROR bad", "INFO ok", "ERROR bad2"]
assert count_errors(lines) == 2
def test_count_errors_empty():
assert count_errors([]) == 0
def test_count_errors_no_errors():
assert count_errors(["INFO ok", "DEBUG verbose"]) == 0
EOF
cat > requirements.txt << 'EOF'
# No runtime dependencies for this practice service
EOF
cat > requirements-dev.txt << 'EOF'
pytest==8.1.1
pytest-cov==5.0.0
ruff==0.3.0
EOF
cat > Dockerfile << 'EOF'
FROM python:3.11-slim
WORKDIR /app
COPY src/ src/
CMD ["python", "-c", "from src.counter import count_errors; print('OK')"]
EOFExercise: Write .github/workflows/ci.yml implementing:
lintjob: ruff check.testjob (needs lint): pytest with--cov-fail-under=80.dependency-scanjob (needs test): pip-audit.- Path filter: only trigger on changes to
src/,tests/,requirements*.txt, or the workflow file itself.
Full solution: Use the complete pipeline YAML from §7 as reference, adapting the paths and job names to this minimal project. The solution is intentionally left as a construction exercise; the worked pipeline earlier in this lesson is the answer key.
Independent Practice
Task: The Northline report-exporter service has no CI pipeline. It has 42 Python files, requirements.txt (22 dependencies), and a Dockerfile. Create a CI pipeline YAML for it that:
- Triggers on PRs to
mainand pushes tomain. - Has a lint stage, a test stage (80 % coverage threshold), and a dependency scan stage.
- Caches pip dependencies correctly.
- Uploads the coverage report and audit report as artefacts.
- Uses least-privilege
permissions:(read contents, write pull-requests). - Does not use
|| trueanywhere. - Has a
concurrency:block to cancel stale runs.
Acceptance criteria:
- YAML is syntactically valid (validate with
python3 -c "import yaml; yaml.safe_load(open('.github/workflows/ci.yml'))"locally). - All three stages are present.
needs:dependencies are correct (lint → test → dependency-scan).- No secrets are hardcoded in the YAML.
|| truedoes not appear in anyrun:block.- Artefact retention period is set to 14 days.
Common Mistakes
- Using
|| trueto silence test failures. This is the single most dangerous anti-pattern in CI configuration. Mark it as forbidden in your code-review checklist. - Not pinning Action versions.
uses: actions/checkout@mainwill silently change behaviour when the Action is updated. Always use a specific version tag (e.g.,@v4) or a commit SHA. - Setting coverage threshold too low to be meaningful. A threshold of 10 % gates almost nothing. Start at the current coverage baseline and increase it with each release.
- Not uploading artefacts with
if: always(). If the test step fails, the coverage report is not generated in the default path — and if you do not upload withif: always(), you lose the partial report that explains what failed. - Overly broad
permissions:. Defaultwrite-allpermissions expose theGITHUB_TOKENto unnecessary scopes. Minimise permissions per workflow. - Caching without a proper cache key. A cache key that never changes (e.g.,
key: pip-${{ runner.os }}) causes stale dependencies to be used even afterrequirements.txtchanges. Always include a hash of the dependency files. - Scanning only Python dependencies and not the container. OS packages in the base image (e.g.,
python:3.11-slim) also have CVEs. Bothpip-auditand a container scan (Trivy, Grype) are needed.
Five Quick Checks
Q1. A pipeline has four sequential jobs: lint → test → dep-scan → container-scan. The test job fails. Which subsequent jobs run?
A1. None. Because of needs: dependencies, dep-scan requires test to succeed. dep-scan is skipped; container-scan is skipped. Only the four jobs up to the point of failure run.
Q2. What is the difference between a CI artefact and a CI cache?
A2. A cache speeds up repeated steps by reusing outputs between runs (e.g., installed packages); it is automatically evicted. An artefact is a preserved output for inspection or use by later jobs (e.g., a coverage report); it is retained for a configured period.
Q3. Why should path filters be used on CI pipelines?
A3. To avoid running expensive CI jobs when only unrelated files change (e.g., documentation). This reduces runner usage, cost, and developer wait time.
Q4. A developer finds that the test job always shows green even when tests are failing. What is the most likely cause in the YAML?
A4. The run: command for pytest includes || true (or ; true) at the end, which masks the non-zero exit code. The step always exits 0 regardless of test outcome.
Q5. The GITHUB_TOKEN in a workflow run has permissions: contents: write. Why is this problematic if the pipeline also runs pull requests from external contributors (forks)?
A5. Fork PR pipelines with write permissions can allow a malicious PR author to write back to the repository. Restrict permissions to contents: read for PR pipelines; only grant write permissions to jobs that specifically need to push (e.g., release jobs triggered from main only).
Quiz Alignment
| Objective | Quick Check | Practice task |
|---|---|---|
| CI triggers | Q3 | Guided practice — trigger section |
Stage design and needs: | Q1 | Full pipeline YAML |
| Artefact vs. cache | Q2 | Full pipeline YAML — cache and upload steps |
| False-green prevention | Q4 | Failure Scenario |
| Pipeline secrets and permissions | Q5 | Full pipeline YAML — permissions: block |
| Reading failures | — | Worked Example A, Worked Example B |
| Quality gate thresholds | — | --cov-fail-under=80, severity: CRITICAL,HIGH |
Lesson Takeaways
- A CI pipeline is only as valuable as its honesty. A false-green pipeline is more dangerous than no pipeline because it creates misplaced trust.
- The four-stage pattern (lint → test → dependency scan → container scan) addresses four distinct vulnerability surfaces: code style bugs, logic bugs, known dependency vulnerabilities, and OS-level container vulnerabilities.
|| trueon a test step is the single most common CI anti-pattern. Treat it as a code smell in every PR review.- Pin all Action versions to specific tags. Floating references silently change behaviour.
- Secrets must be injected at runtime via platform secret management, never stored in YAML. Minimise token scope with explicit
permissions:. - Fast pipelines get used; slow pipelines get bypassed. Cache pip dependencies, use path filters, and keep the PR-gate under 5 minutes.
Bridge to Subsequent Lessons
This lesson completes the four-lesson foundation of the DevOps & Platform Engineering course. The skills stack vertically:
- #devops1 gave you the vocabulary and lifecycle map.
- #devops2 gave you the command-line skills to work inside pipeline environments.
- #devops3 gave you the branch governance that feeds the pipeline.
- This lesson gave you the pipeline itself — the automated immune system that validates every change.
Future lessons in this course build on this foundation into containerisation, Kubernetes deployment patterns, observability, and infrastructure as code. See the course index for the full sequence.