🐍 Python for Everyone

← Back to all chapters

Chapter 30 of 33 Intermediate 70 min read

CI/CD Pipelines

Chapters 27–29 gave you three separate pieces: automated tests (Chapter 27), local git (Chapter 28), and pull requests hosted on GitHub (Chapter 29). This chapter wires them together so they run themselves. There's no new Python syntax here — the new language is YAML, and the new tool is GitHub Actions, which runs your pytest suite automatically, on GitHub's own servers, every time someone pushes or opens a PR, without anyone having to remember to run it by hand.

How to read this chapter

Chapter 27 gave your project a real test suite. Chapter 29 gave it pull requests. Now picture the gap between them: a contributor opens a PR, their laptop happens to have a slightly different package version installed, and their tests passed locally — but they never actually ran pytest before pushing, because remembering to is easy to skip under a deadline. The PR gets reviewed on the diff alone, looks fine, and merges. Two days later, main is broken for everyone. This chapter is about removing "did someone remember to run the tests" from that story entirely — by having a machine run them, automatically, on every single push, whether anyone remembers or not.
Sub-topic 1 of 6

1. Why CI/CD matters

At a glance
  • "Works on my machine" is a real, common failure — different installed package versions, different OS, different environment variables, all invisible until code runs somewhere else.
  • Without automation, tests only get run when a human remembers to — and under time pressure, that's exactly when they get skipped.
  • Manual deploys repeat the same class of mistake at a higher cost: a forgotten step, a stale build, a file deployed from the wrong branch.
Why this matters: every failure mode below has the same root cause — a correctness check that exists, but only runs when a human remembers to trigger it by hand. CI/CD's entire value proposition is turning "remember to" into "automatically, every time."
What is... CI/CD? CI (Continuous Integration) means automatically building and testing every change as soon as it's pushed, so problems surface within minutes, not after they've piled up. CD (Continuous Delivery/Deployment) extends that automation further, to packaging and shipping a change once it passes. This chapter focuses mostly on the CI half — an automated lint + test workflow — since that's the part every project benefits from immediately, and touches on CD conceptually in Sub-topic 6.

"Works on my machine" is the most common version of this problem. It happens for reasons that have nothing to do with whether the code is actually correct:

None of these are hypothetical — they're the ordinary, daily reality of more than one person touching the same codebase. The fix isn't "be more careful"; it's running every check in one identical, disposable environment, every time, regardless of whose machine the change came from.

the gap this chapter closes
Without CI/CD:                      With CI/CD:

  write code                          write code
  (maybe) run tests locally           push
  push                                   |
  open PR                                v
  reviewed on the diff alone       GitHub Actions runs the
  merged                           full test suite automatically,
  ...bug discovered later,         on a clean machine, in minutes
  after it's already shared           |
                                       v
                                  PR shows pass/fail BEFORE
                                  a human ever has to guess

The same logic applies to deployment. A manual deploy is a human running a checklist by hand — build the project, copy the right files, restart the right service — and every one of those steps is a place a tired or rushed human can skip something or run it against the wrong branch. An automated deploy pipeline runs the exact same steps, in the exact same order, every time, with no step silently forgotten.

This is precisely the scenario from the hook: a contributor's local pytest run (Chapter 27) and their pushed branch (Chapter 28) are only useful to the team once something confirms they actually agree — and that confirmation needs to happen automatically, on GitHub, not rely on the contributor's memory or the reviewer's trust.

Go Deeper: is GitHub Actions the only CI/CD tool?

No — Jenkins, GitLab CI/CD, CircleCI, and Travis CI are all widely used alternatives, and the underlying ideas (trigger on a push, run in a clean environment, report pass/fail) are shared across all of them. GitHub Actions is covered here specifically because it's built directly into GitHub (Chapter 29's platform), needs no separate account or service, and is free for public repositories — making it the lowest-friction way to add real CI to a project you're already hosting there.

Quick recap
  • "Works on my machine" bugs come from environment differences that only a clean, identical, automated environment reliably catches.
  • Tests and deploy steps that only run when a human remembers eventually get skipped under pressure — automation removes that dependency.
  • CI automatically builds/tests every change; CD extends that automation to packaging and shipping it.
Sub-topic 2 of 6

2. GitHub Actions basics

At a glance
  • A GitHub Actions workflow is a YAML file in .github/workflows/ describing when to run, and what to do.
  • on defines the trigger; jobs defines what runs; each job's steps define, in order, the individual commands or actions to execute.
  • A runner is the actual machine (a fresh virtual machine GitHub provisions per run) that executes a job's steps.
Why this matters: every workflow file, no matter how complex, is built from exactly these three concepts — trigger, jobs, steps — nested inside one YAML file. Sub-topic 3 builds a real one from these same pieces.

A workflow file lives at a specific, required path: .github/workflows/<anything>.yml. GitHub scans that folder in every repository and treats every .yml file inside it as a workflow definition. The simplest possible one is barely more than its trigger and one command:

.github/workflows/hello.yml
name: Basic CI

on: push

jobs:
  say-hello:
    runs-on: ubuntu-latest
    steps:
      - name: Print a greeting
        run: echo "Hello from GitHub Actions"
What is... a workflow? A workflow is one YAML file describing an automated process: what event should trigger it (on), and what work to do when it fires (jobs). A repository can have many workflow files at once — one for tests, a separate one for deployment, another for a scheduled nightly task — each triggered independently.

Reading that file top to bottom: name is just a human-readable label, shown in GitHub's UI. on: push is the trigger — this workflow runs on every push, to any branch. Real projects are almost always more specific than that, scoping the trigger to particular branches and events:

a more realistic trigger
on:
  push:
    branches: [main]
  pull_request:
    branches: [main]

This runs the workflow in two situations: a direct push to main, and any pull request whose target branch is main — which is exactly the moment a PR from Chapter 29 needs a pass/fail result attached to it, before anyone reviews the diff by eye.

Thought process: the decision that matters isn't YAML syntax, it's scoping the trigger correctly — running a workflow on every push to every branch wastes runner minutes on throwaway branches, while running it only on main misses the whole point of catching problems before they merge. Triggering on both a push to main and any PR targeting main is the standard shape almost every real project uses.

Write the prompt you'd give an AI assistant to build this:

Show a strong version of this prompt
Write just the `on:` trigger section of a GitHub Actions workflow YAML file. It should run the workflow in two cases: (1) a direct push to the `main` branch, and (2) any pull request that targets `main` as its base branch. Use the `branches:` filter under both `push` and `pull_request` so it doesn't fire on every branch. Show the YAML and briefly explain why scoping the trigger this way avoids wasting CI minutes on unrelated branches.

Inside jobs, each named entry (say-hello above) is one independent unit of work. runs-on picks the machine it executes on:

What is... a runner? A runner is the actual virtual machine GitHub provisions to execute a job. runs-on: ubuntu-latest is by far the most common choice — a fresh Ubuntu Linux VM, spun up from scratch for that one run and destroyed afterward, so nothing from a previous run (leftover files, cached state, environment drift) ever leaks in. GitHub also offers Windows (windows-latest) and macOS (macos-latest) runners for projects that need to test on those platforms specifically.

Each job gets its own fresh runner. That distinction matters once a workflow has more than one job:

What is... a job? A job is a set of steps that run together, in order, on the same runner. Jobs run in parallel by default unless one explicitly depends on another (via needs, covered in Sub-topic 6) — which is why splitting unrelated work (say, linting and a security scan) into separate jobs can finish faster than cramming everything into one.

Finally, steps is an ordered list, and each step is one of exactly two things: a shell command (run), or a reusable, pre-built action (uses). The two actions almost every Python workflow starts with are actions/checkout and actions/setup-python:

.github/workflows/checkout-setup.yml
name: Checkout and set up Python

on: push

jobs:
  build:
    runs-on: ubuntu-latest
    steps:
      - name: Check out the repository
        uses: actions/checkout@v4

      - name: Set up Python
        uses: actions/setup-python@v5
        with:
          python-version: "3.12"

      - name: Confirm Python is available
        run: python --version
What is... a step? A step is one action within a job, run in order top to bottom. A step either runs a shell command directly (run: pytest) or invokes a reusable, versioned action published by GitHub or the community (uses: actions/checkout@v4), optionally passing it inputs via with. The @v4/@v5 suffix pins a specific major version of that action — the same reason Chapter 27's requirements.txt pins dependency versions, so a workflow doesn't silently break when an action publishes a breaking change.

A fresh runner starts completely empty — it does not automatically have your repository's code on it. actions/checkout@v4 is the step that clones your repository onto the runner (the same clone operation Chapter 29 covered, just run by GitHub instead of you). actions/setup-python@v5 then installs the requested Python version and puts it on the runner's PATH, so every step after it can run python and pip normally. Almost every job in this chapter starts with these same two steps, in this same order — checkout has to come first, since there's nothing to set up Python for otherwise.

Go Deeper: what other events can trigger a workflow besides push and pull_request?

Plenty — schedule (a cron expression, for a nightly or weekly run), workflow_dispatch (a manual "Run workflow" button in GitHub's UI, useful for deploys you want to trigger deliberately rather than automatically), release (when a GitHub release is published), and issues (when an issue from Chapter 29 is opened or labeled) are all common ones. A single workflow's on block can list several of these together, each with its own filters.

Quick recap
  • A workflow file lives at .github/workflows/*.yml and is built from a trigger, jobs, and each job's steps.
  • A runner is a fresh, disposable VM; a job is an ordered list of steps that run on one runner.
  • actions/checkout@v4 then actions/setup-python@v5 is the standard opening pair of steps for a Python workflow.
Sub-topic 3 of 6

3. Building a lint + test workflow

At a glance
  • A real CI workflow, put together from Sub-topic 2's pieces: check out the code, set up Python, install dependencies, lint, then test.
  • ruff is a fast, widely-used Python linter; pytest (Chapter 27) is the test runner.
  • The job fails — and blocks, once branch protection is set up in Sub-topic 5 — the moment any single step exits with a non-zero status.
Why this matters: this is the one workflow every project should have from day one — everything else in this chapter (matrix testing, caching, the wider pipeline) is an enhancement on top of exactly this shape, not a replacement for it.

Here's the complete, working workflow this chapter's own exercises are built around — nothing in it goes beyond what Sub-topic 2 already introduced:

.github/workflows/ci.yml
name: Lint and Test

on:
  push:
    branches: [main]
  pull_request:
    branches: [main]

jobs:
  lint-and-test:
    runs-on: ubuntu-latest
    steps:
      - name: Check out the repository
        uses: actions/checkout@v4

      - name: Set up Python
        uses: actions/setup-python@v5
        with:
          python-version: "3.12"

      - name: Install dependencies
        run: |
          python -m pip install --upgrade pip
          pip install -r requirements.txt
          pip install ruff pytest

      - name: Lint with ruff
        run: ruff check .

      - name: Run tests with pytest
        run: pytest

Two things worth noticing about the run steps. First, the | after run: in "Install dependencies" is plain YAML syntax for a multi-line string — each line becomes its own command, run in sequence, in the same shell. Second, the order of the last two steps is deliberate: lint before test. Linting is far faster than running a full test suite, so catching a trivial style or syntax issue there means the workflow fails fast, before spending runner time on tests that were never going to matter if the lint step was going to fail anyway.

What is... a linter, in this context? A linter statically analyzes code for issues without running it — unused imports, undefined names, inconsistent style, common bug patterns (like Chapter 25's mutable-default-argument gotcha). ruff is a modern, extremely fast linter for Python (a single ruff check . scans an entire project in milliseconds); it's used here as the concrete example, but the same workflow shape applies with flake8 or any other linter — only the install line and the one run command change.

Running ruff check . against a file with an actual issue makes the pass/fail behavior concrete:

app.py (has an unused import)
import os
import json

def load_config(path):
    with open(path) as f:
        return json.load(f)
ruff check . output
app.py:1:8: F401 [*] `os` imported but unused
Found 1 error.
[*] 1 fixable with the `--fix` option.

That non-zero exit status is exactly what makes the whole workflow useful: any step that fails stops the job right there and marks it red, and every subsequent step in that job is skipped. GitHub Actions doesn't need any special "did it pass" logic — it's using the same success/failure convention every command-line tool already follows, the same one that makes pytest's own exit code meaningful when you run it locally.

Thought process: the actual engineering decision in this workflow is step ordering and scope, not YAML mechanics — lint before test because it's cheaper and fails faster; one job, not several, because lint and test share the same installed dependencies and there's no benefit to paying for a second runner setup just to split them apart here (Sub-topic 6 shows when splitting into separate jobs does pay off).

Write the prompt you'd give an AI assistant to build this:

Show a strong version of this prompt
Write a GitHub Actions workflow file, .github/workflows/ci.yml, for a Python project. Requirements: (1) trigger on push to main and on any pull_request targeting main, (2) one job named lint-and-test running on ubuntu-latest, (3) steps in this exact order: actions/checkout@v4, actions/setup-python@v5 configured for Python 3.12, a step that upgrades pip and installs both requirements.txt and the packages ruff and pytest, a step that runs `ruff check .`, and a final step that runs `pytest`. Explain why lint should run before pytest in the step order, and confirm the YAML is valid by describing how you'd check it with yaml.safe_load() in Python.
Go Deeper: why pip install ruff pytest instead of putting them in requirements.txt?

Many real projects do exactly that — but a common convention is keeping requirements.txt limited to what the application itself needs to run, and listing dev-only tools (linters, test frameworks, formatters) either directly in the workflow, or in a separate file like requirements-dev.txt installed only in CI. Either approach is valid; what matters is that whichever one a project picks, the workflow installs everything the lint and test steps actually need before running them.

Quick recap
  • A complete lint + test workflow is just Sub-topic 2's building blocks in a deliberate order: checkout, setup-python, install, lint, test.
  • Lint runs before test because it's faster and fails cheaper.
  • A non-zero exit from any step fails that step, stops the job, and skips whatever comes after — the same convention as any other CLI tool's exit code.
Sub-topic 4 of 6

4. Workflow matrix and caching

At a glance
  • A matrix strategy runs the same job multiple times, once per combination of values (e.g. one run per Python version) — in parallel, not one after another.
  • This catches version-specific bugs Sub-topic 3's single-version workflow can't — "works on 3.12" isn't the same claim as "works on every Python version this project supports."
  • Caching pip's downloaded packages between runs cuts install time, since the same dependencies rarely change from one run to the next.
Why this matters: Sub-topic 3's workflow only proves the code works on one specific Python version — for any project that supports (or claims to support) more than one, that's an unverified claim, not a tested fact, until a matrix actually runs it on each.
What is... a matrix strategy? A matrix strategy tells GitHub Actions to run one job multiple times, substituting a different value into it each time, from a list you define. The most common use is testing several Python versions, but a matrix can vary any combination of values at once (Python version and operating system, for example) — GitHub runs every combination as its own separate, parallel job.

Adding a matrix to Sub-topic 3's workflow needs exactly two additions: a strategy.matrix block, and a reference to that matrix's value wherever the single, hardcoded version used to be:

.github/workflows/ci.yml (with a matrix and caching)
name: Lint and Test (matrix)

on:
  push:
    branches: [main]
  pull_request:
    branches: [main]

jobs:
  lint-and-test:
    runs-on: ubuntu-latest
    strategy:
      matrix:
        python-version: ["3.10", "3.11", "3.12"]
    steps:
      - name: Check out the repository
        uses: actions/checkout@v4

      - name: Set up Python ${{ matrix.python-version }}
        uses: actions/setup-python@v5
        with:
          python-version: ${{ matrix.python-version }}
          cache: "pip"

      - name: Install dependencies
        run: |
          python -m pip install --upgrade pip
          pip install -r requirements.txt
          pip install ruff pytest

      - name: Lint with ruff
        run: ruff check .

      - name: Run tests with pytest
        run: pytest

${{ matrix.python-version }} is GitHub Actions' expression syntax — it substitutes in whichever value from the matrix list this particular parallel run is handling. With three versions listed, this one job definition produces three independent runs: lint-and-test (3.10), lint-and-test (3.11), lint-and-test (3.12), each on its own fresh runner, all starting at the same time:

what the matrix produces -- three parallel runs from one job definition
jobs.lint-and-test  (matrix: python-version)
  |
  +-- lint-and-test (3.10)  -- own runner, runs independently
  +-- lint-and-test (3.11)  -- own runner, runs independently
  +-- lint-and-test (3.12)  -- own runner, runs independently

All three run in parallel -- total time is roughly the SLOWEST
one, not the sum of all three.

Thought process: the version list itself is the real decision, not the matrix syntax — it should match whatever a project actually claims to support (often documented in pyproject.toml's python_requires or a README), not an arbitrary "add a few versions." Listing versions the project doesn't actually support wastes CI time testing combinations no user will ever run.

Write the prompt you'd give an AI assistant to build this:

Show a strong version of this prompt
Here is my existing GitHub Actions workflow (paste the ci.yml from Sub-topic 3). Modify it to: (1) add a strategy.matrix block that runs the job against Python 3.10, 3.11, and 3.12, (2) reference the matrix value with ${{ matrix.python-version }} in both the job's setup-python step name and its python-version input, and (3) enable pip caching via actions/setup-python's built-in cache: "pip" option rather than a separate caching action. Explain what "each matrix combination runs on its own runner, in parallel" actually means for total workflow time versus running the three versions one after another.
What is... caching, in a workflow? Every runner starts completely empty, so without caching, "Install dependencies" downloads every package from scratch on every single run — even when requirements.txt hasn't changed since yesterday. cache: "pip" on actions/setup-python@v5 is the simplest way to fix this: it automatically saves pip's download cache after a run and restores it at the start of the next one (keyed on a hash of your dependency file), so unchanged dependencies are pulled from the cache instead of re-downloaded from the internet.

The effect compounds with the matrix above: three parallel jobs each installing the same dependencies would otherwise mean three full, repeated downloads every single run; with caching enabled, only the very first run (or any run after requirements.txt changes) pays that full cost.

Go Deeper: what invalidates the pip cache?

By default, actions/setup-python's built-in caching keys the cache to a hash of your dependency file (requirements.txt, or pyproject.toml/poetry.lock for other setups). Change one character in requirements.txt — bump a version pin, add a new package — and the hash changes, so the next run gets a fresh cache miss and rebuilds it once. This is exactly the right invalidation rule: dependencies genuinely did change, so a stale cache would be actively wrong to reuse.

Quick recap
  • A matrix strategy tests every version combination as its own parallel run, from one job definition.
  • Matrixed runs happen in parallel — total time tracks the slowest one, not the sum.
  • Pip caching (cache: "pip") skips re-downloading unchanged dependencies, keyed on your dependency file's hash.
Sub-topic 5 of 6

5. Status checks and branch protection

At a glance
  • Every workflow run against a PR shows up directly on that PR as a status check — pass, fail, or still running.
  • By default, a status check is purely informational — a red X doesn't stop anyone from merging.
  • Branch protection with required status checks is what actually turns a passing workflow into a hard requirement before a merge button becomes clickable.
Why this matters: Sub-topics 3–4 built a workflow that reports pass/fail accurately — but a report nobody is required to look at doesn't actually prevent the hook's broken-merge scenario. Branch protection is the piece that closes that gap for real.

Once a workflow like Sub-topic 3's is committed to .github/workflows/, GitHub runs it automatically on every matching push and PR — no extra setup needed to make it run. What it looks like on a real pull request:

Illustrative text mockup — not a real screenshot

A stand-in for GitHub's real PR "Checks" section, described in prose/structure since it can't be captured as a real screenshot here.

Pull Request #57 — Add shopping list feature

  Some checks haven't completed yet
  1 pending, 0 failing, 2 successful checks

    ✓ lint-and-test (3.10)          38s
    ✓ lint-and-test (3.11)          41s
    ⏳ lint-and-test (3.12)         running...

  [ Merge pull request ]  (still clickable -- not required yet)
What is... a status check? A status check is the pass/fail (or still-running) result of one workflow job, attached directly to the specific commit it ran against and shown on any PR containing that commit. Each matrix combination from Sub-topic 4 reports as its own separate check (lint-and-test (3.10), lint-and-test (3.11), etc.), so a reviewer can see exactly which Python version, if any, actually failed — not just one combined red/green result.

Notice the mockup's merge button: still clickable, even with a check pending. That's the default, and it's a real gap — a red X or a still-running check is only useful information if someone is required to wait for it. Branch protection is the GitHub repository setting that closes that gap:

What is... branch protection? Branch protection is a set of rules attached to a specific branch (almost always main) that GitHub enforces regardless of who's pushing or merging. Required status checks is one such rule: it names specific checks (like lint-and-test (3.12)) that must report success before the merge button becomes clickable at all — turning Sub-topic 3's workflow from a report into an actual gate.
Illustrative text mockup — not a real screenshot

A stand-in for GitHub's real branch protection settings page and its effect on a PR, described in prose/structure.

Settings > Branches > Branch protection rule for "main"

  [x] Require status checks to pass before merging
      [x] Require branches to be up to date before merging

      Status checks that are required:
        [x] lint-and-test (3.10)
        [x] lint-and-test (3.11)
        [x] lint-and-test (3.12)

  ---------------------------------------------------------

  Pull Request #58 — Fix off-by-one in total()

    ✗ lint-and-test (3.11)          FAILED — 1 test failed

  Merge blocked
  Required status check "lint-and-test (3.11)" is failing.
  [ Merge pull request ]  (button disabled, greyed out)

Thought process: the judgment call in branch protection isn't "should I turn it on" (almost always yes, for any shared branch) — it's exactly which checks to mark required. Marking a flaky or still-experimental check as required blocks every future merge on something unreliable; the right default is requiring only checks that are both stable and genuinely meaningful, like every matrix combination of the lint-and-test job.

Write the prompt you'd give an AI assistant to help with this:

Show a strong version of this prompt
My repository has a GitHub Actions workflow, lint-and-test, that runs as a matrix across Python 3.10, 3.11, and 3.12 -- so it reports three separate status checks per PR (lint-and-test (3.10), (3.11), (3.12)). Walk me through the exact steps in GitHub's Settings > Branches to add a branch protection rule for main that: (1) requires all three of those specific checks to pass before the merge button is enabled, and (2) requires the branch to be up to date with main before merging. Explain what "require branches to be up to date" actually prevents that requiring the checks alone doesn't.

"Require branches to be up to date before merging" is worth calling out specifically: it forces a PR branch to have the latest main merged or rebased in (Chapter 28's territory again) before its checks count, closing one more real gap — a PR that passed CI a week ago, before main changed underneath it, isn't proof it still passes today.

Go Deeper: can an admin bypass a required status check?

By default, repository admins can still merge past a failing required check — branch protection has a separate "Do not allow bypassing the above settings" option that closes even that door, applying the rule to everyone including admins. Most real teams leave admins able to bypass in a genuine emergency, but treat doing so as rare and notable, not routine — if bypassing a required check becomes normal, the check has effectively stopped meaning anything.

Quick recap
  • A status check is a workflow run's pass/fail result, shown directly on the PR that triggered it.
  • Status checks alone don't block anything — branch protection's "required status checks" is what does.
  • "Require branches to be up to date" closes the gap where a PR passed CI before main changed underneath it.
Sub-topic 6 of 6

6. Beyond tests: the wider pipeline

At a glance
  • "CI/CD" covers far more than running pytest — type checking, security scanning, building distributable artifacts, and deploying are all common pipeline stages.
  • Independent checks (lint/test, type checking, security scanning) are usually split into separate parallel jobs; a build or deploy stage that depends on all of them uses needs to wait until they succeed.
  • This sub-topic is conceptual — each stage is a real, runnable pattern, but going deep on any one of them (a full deployment pipeline, a specific security scanner) is beyond this chapter's scope.
Why this matters: every prior sub-topic built one job. A real production pipeline is usually several jobs working together, some in parallel, some gated on others — this is the shape that connects everything else in this chapter into one coherent picture.

Beyond lint and test, four more stages show up constantly in real pipelines:

Put together, with lint-and-test's matrix from Sub-topic 4 alongside three new jobs:

.github/workflows/pipeline.yml
name: Full Pipeline

on:
  push:
    branches: [main]
  pull_request:
    branches: [main]

jobs:
  lint-and-test:
    runs-on: ubuntu-latest
    strategy:
      matrix:
        python-version: ["3.10", "3.11", "3.12"]
    steps:
      - uses: actions/checkout@v4
      - uses: actions/setup-python@v5
        with:
          python-version: ${{ matrix.python-version }}
          cache: "pip"
      - run: pip install -r requirements.txt
      - run: ruff check .
      - run: pytest

  type-check:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - uses: actions/setup-python@v5
        with:
          python-version: "3.12"
      - run: pip install mypy -r requirements.txt
      - run: mypy .

  security-scan:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - uses: actions/setup-python@v5
        with:
          python-version: "3.12"
      - run: pip install pip-audit
      - run: pip-audit -r requirements.txt

  build:
    needs: [lint-and-test, type-check, security-scan]
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - name: Build distribution
        run: python -m build
      - name: Upload build artifact
        uses: actions/upload-artifact@v4
        with:
          name: dist
          path: dist/
What is... needs? needs makes a job wait for one or more other jobs to succeed before it starts, instead of running immediately in parallel with everything else. Here, build lists all three earlier jobs in its needs — it only runs once lint-and-test (all three matrix combinations), type-check, and security-scan have all reported success. If any of them fails, build is skipped entirely, so a broken or vulnerable commit never gets packaged in the first place.
the shape of this pipeline
lint-and-test (3.10)  \
lint-and-test (3.11)   |-- all run in PARALLEL, independent of
lint-and-test (3.12)  /    each other and of the two jobs below
type-check            |
security-scan         /
        |
        | needs: [lint-and-test, type-check, security-scan]
        v
      build   -- only runs if EVERY job above succeeded

actions/upload-artifact@v4 is the last new piece: it saves whatever's in the given path (here, dist/, where Python's standard build tool puts a built wheel and source distribution) as a downloadable artifact attached to that specific workflow run — retrievable later from GitHub's UI, or by a following deployment job. A real deployment stage would typically follow this same needs pattern one level further: a deploy job that needs: [build], downloads the artifact, and ships it — often restricted to only run on pushes to main (not every PR) via an if condition, and frequently requiring a manual approval through GitHub's environments feature before it's allowed to touch production.

Thought process: the real design decision across a multi-job pipeline is what runs in parallel versus what's gated — lint/type-check/security-scan share no dependency on each other's results, so there's no reason to force them to run in sequence and waste time; build genuinely does depend on all three passing, so it's the one place `needs` belongs. Getting this wrong either wastes CI time (unnecessary sequencing) or wastes compute on doomed work (building an artifact from code that fails its own tests).

Write the prompt you'd give an AI assistant to build this:

Show a strong version of this prompt
Extend my existing matrix lint-and-test workflow (paste the Sub-topic 4 YAML) into a full pipeline with these additional jobs, all in the same workflow file: (1) a type-check job on ubuntu-latest with Python 3.12 that installs mypy plus requirements.txt and runs `mypy .`, (2) a security-scan job that installs pip-audit and runs `pip-audit -r requirements.txt`, (3) a build job that uses `needs: [lint-and-test, type-check, security-scan]` so it only runs after all three succeed, checks out the repo, runs `python -m build`, and uploads the resulting dist/ folder using actions/upload-artifact@v4. Explain why lint-and-test, type-check, and security-scan should run in parallel rather than one after another, and why build specifically needs the `needs` key when the others don't.
Go Deeper: what's the difference between Continuous Delivery and Continuous Deployment?

Both build on the same automated pipeline; they differ only in the very last step. Continuous Delivery means every change that passes the pipeline is automatically packaged and ready to ship, but a human still clicks the button that actually releases it (matching the manual-approval environment mentioned above). Continuous Deployment goes one step further and removes even that click — a change that passes every stage ships to production automatically, with no human gate at all. Most teams start with delivery and only move to full deployment once they trust their pipeline's coverage enough to remove the last manual checkpoint.

Quick recap
  • Real pipelines extend lint + test with type checking, security scanning, build artifacts, and deployment stages.
  • Independent stages run as parallel jobs; needs gates a job (like a build) on one or more others succeeding first.
  • Continuous Delivery automates everything up to a human-approved release; Continuous Deployment removes that last manual step too.
In the Real World

Points to Remember

← All Chapters Take the Quiz →