Rana Maninder Singh
Lesson 4 of 12DevOps & Platform Engineering

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:

  1. Explain what triggers a CI pipeline and how trigger rules control when jobs run.
  2. Design a multi-stage pipeline with lint, unit test, security scan, and dependency scan stages.
  3. Distinguish between artefact caching and artefact storage, and explain when each applies.
  4. Set and enforce quality gate thresholds (test coverage, vulnerability severity).
  5. Identify the causes of false-green pipelines and apply corrections.
  6. Manage pipeline secrets safely using environment-injected variables and least-privilege token scopes.
  7. 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

ConceptWhere to learn it
DevOps delivery lifecycleLesson 1 — DevOps & Platform Engineering #devops1
Shell scripting, exit codes, environment variablesLesson 2 — Linux & Bash #devops2
Branch protection, pull requests, secrets preventionLesson 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.

LevelDescription
WorkflowA YAML file in .github/workflows/. Triggered by events. Contains one or more jobs.
JobA set of steps that runs on a single runner (virtual machine or container). Jobs run in parallel by default.
StepA single shell command or a pre-built Action. Steps within a job run sequentially.
RunnerThe 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: true

This 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: 14

Coverage 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: 14

pip-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: 14

Trivy 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.txt

Cache key design:

4.3 Caching vs. artefact storage

CacheArtefact
PurposeSpeed up repeated steps by reusing unchanged outputsPreserve job outputs for inspection, download, or use in later jobs/workflows
EvictionAutomatic (oldest evicted when quota is reached)After configured retention period
Use between PRsYes — cache is shared across branchesCan 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

CauseMechanismSymptom
Tests removed to make them passDeveloper deletes test or marks it xfail/skip without justificationCoverage drops but threshold not enforced; no review of skipped tests
Coverage threshold too low--cov-fail-under=10 passes code with minimal tests95 % of code paths untested
Flaky tests `true`-d`pytest ...true` silently ignores test failuresPipeline always green regardless of test outcome
Hardcoded fixture instead of real logicTests assert against hardcoded strings, not computed outputTests pass even when the logic is completely broken
Dependency scan skipped for "legacy" codeAn exception list grows uncheckedKnown vulnerabilities persist in production
Pipeline timeout too shortJobs 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

  1. Enforce minimum coverage and increase it gradually as the test suite matures.
  2. Require justification for skipped tests in PR review: any pytest.mark.skip or pytest.mark.xfail added in a PR must have a linked ticket in the reason string.
  3. Never use || true on test steps. If a job must be allowed to fail without blocking merge, use GitHub Actions' continue-on-error: true with a separate notification step — make the failure visible, not silent.
  4. Audit the pipeline YAML in code review with the same rigour as application code. A pipeline change that adds || true or removes a required check is a security and quality regression.
  5. 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_TOKEN

never print secrets. echo $DEPLOY_TOKEN will 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: none

Default 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

  1. Check which job failed in the workflow summary view — not all jobs, just the one with the red ×.
  2. Expand the failing step within that job — GitHub Actions shows step-level pass/fail.
  3. Read the last 20 lines of the failing step's output — errors almost always surface at the end.
  4. Search for the first non-zero exit code — the line immediately before the process exit is usually the error.
  5. 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.txt

7.3 Common failure signatures

Symptom in logLikely 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 deniedScript not executable (chmod +x); or step writing to a read-only path
exit code 137Out-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 exceededPyPI or GitHub API rate limit; add retry logic or a cache
Scan step fails with no CVEs listedWrong 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:

  1. Open the test job artefact: test-results.xml and coverage.xml.
  2. The JUnit XML shows two failing tests and the coverage report shows src/consumer/router.py at 12 % coverage.
  3. The developer added router.py in this PR but wrote no tests for it.

Correction:

  1. Write unit tests for router.py that bring its coverage to ≥ 80 %.
  2. Fix the two failing assertions (unrelated to coverage — the DLQ retry logic has a bug).
  3. 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:

  1. Read the audit report artefact.
  2. The installed version is 1.9.0; 2.3.1 is the patched version.
  3. 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.yml

Finding: 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:

Correction:

  1. Remove || true.
  2. Run tests locally; fix the three breaking changes (separate PRs, each with clear commit messages).
  3. 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')"]
EOF

Exercise: Write .github/workflows/ci.yml implementing:

  1. lint job: ruff check.
  2. test job (needs lint): pytest with --cov-fail-under=80.
  3. dependency-scan job (needs test): pip-audit.
  4. 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:

  1. Triggers on PRs to main and pushes to main.
  2. Has a lint stage, a test stage (80 % coverage threshold), and a dependency scan stage.
  3. Caches pip dependencies correctly.
  4. Uploads the coverage report and audit report as artefacts.
  5. Uses least-privilege permissions: (read contents, write pull-requests).
  6. Does not use || true anywhere.
  7. Has a concurrency: block to cancel stale runs.

Acceptance criteria:


Common Mistakes

  1. Using || true to silence test failures. This is the single most dangerous anti-pattern in CI configuration. Mark it as forbidden in your code-review checklist.
  2. Not pinning Action versions. uses: actions/checkout@main will silently change behaviour when the Action is updated. Always use a specific version tag (e.g., @v4) or a commit SHA.
  3. 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.
  4. 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 with if: always(), you lose the partial report that explains what failed.
  5. Overly broad permissions:. Default write-all permissions expose the GITHUB_TOKEN to unnecessary scopes. Minimise permissions per workflow.
  6. 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 after requirements.txt changes. Always include a hash of the dependency files.
  7. Scanning only Python dependencies and not the container. OS packages in the base image (e.g., python:3.11-slim) also have CVEs. Both pip-audit and 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

ObjectiveQuick CheckPractice task
CI triggersQ3Guided practice — trigger section
Stage design and needs:Q1Full pipeline YAML
Artefact vs. cacheQ2Full pipeline YAML — cache and upload steps
False-green preventionQ4Failure Scenario
Pipeline secrets and permissionsQ5Full pipeline YAML — permissions: block
Reading failures—Worked Example A, Worked Example B
Quality gate thresholds—--cov-fail-under=80, severity: CRITICAL,HIGH

Lesson Takeaways


Bridge to Subsequent Lessons

This lesson completes the four-lesson foundation of the DevOps & Platform Engineering course. The skills stack vertically:

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.