Free Python developer course
Go from your first line of code to working as a Python developer: projects, testing, data, databases, web apps and APIs, all in your browser.
Test every change automatically, and ship with gates, flags and rollbacks.
How can a test result tell you exactly what is being deployed?
CI checks a particular revision and can produce an immutable artifact. CD promotes that artifact through release gates so the deployed copy matches what was checked.
Revision R passes tests and produces image I
Promote the exact image digest through staging
Production runs the artifact tied to R
Revision R passes tests and produces image I
Promote the exact image digest through staging
Production runs the artifact tied to R
Given Revision R passes tests and produces image I and Production runs the artifact tied to R, write down the missing step that connects them.
Promote the exact image digest through staging
Now take Promote the exact image digest through staging and the result above. Write an input and an implementation that could produce this trace.
Revision R passes tests and produces image I. Check that your implementation produces the result shown above.
What should a rollback pick if the new revision causes errors?
Use the digest of a previously healthy artifact and verify recovery. Rebuilding the old source may pick up different dependencies or configuration.
Check this when debugging. Rebuilding the artifact for production after testing another build.
On a professional team, nobody's change reaches users until a machine has built it, tested it and checked it, every time. That machine is the CI/CD pipeline. It catches mistakes in minutes instead of in production, lets many people change one codebase safely, and makes shipping routine rather than scary. Teams that deploy many times a day aren't braver; they have better pipelines.
Within minutes, when the pipeline runs the tests on their change
CI builds and tests every change automatically before it can merge, so problems surface while the change is fresh in the author's mind. CD then ships what passes.
This lesson rests on Testing with pytest (a test is a check that fails loudly) and Containers and deployment (the image a pipeline builds and ships). A pipeline is those two ideas run by a machine on every change.
Picture a car factory. Each part gets checked as it's fitted, finished cars wait in the lot until someone orders them released, and at some factories they roll straight out to dealers. Software has the same three stages:
Branch protection makes it binding: the main branch only accepts pull requests whose required checks pass, and often a review too.
>= to >. What does this print when CI runs the cases?def discount(subtotal): return 0.1 if subtotal > 100 else 0.0 cases = [(99, 0.0), (100, 0.1), (150, 0.1)] failed = [subtotal for subtotal, expected in cases if discount(subtotal) != expected] print(failed, "merge" if not failed else "blocked")
[100] blocked
Only the row at exactly 100 fails, and that is enough to block the merge. The other rows would never have noticed the change. Tests protect the main branch only if something runs them on every push, which is the first of this lesson's three terms.
They're skipped, because they need lint (directly or through test)
needs builds a dependency graph. A failure skips everything downstream.
Pick a case and step. In the first, one image travels from build to production. In the third, a rollback is the same deploy with the previous tag.
For AI features, add an eval job when prompts or models change: run the eval set and fail if scores drop below a threshold. Keep it small enough to be cheap, and run the full suite before releases.
Write a sentence or two, then compare it with a good answer in the lesson.
A pipeline is a few small pieces of logic: the order jobs can run in, the jobs a change needs, and the answer a flag gives one user. Each is a few lines of Python.
Say most failures are caught by lint or types. Compare the wait before you hear about a broken change, with slow jobs first and fast jobs first.
# name, minutes, share of failures caught jobs = [("lint", 1, 0.5), ("types", 2, 0.3), ("tests", 12, 0.2)] def expected_wait(order): wait, spent = 0, 0 for name, minutes, share in order: spent += minutes wait += spent * share return wait print("fast first:", round(expected_wait(jobs), 1), "minutes") print("slow first:", round(expected_wait(jobs[::-1]), 1), "minutes")
Same jobs, same total time when everything passes, yet a broken change gets its answer about three times sooner. Those minutes add up across a team, and people stop context-switching while they wait.
Jobs in the same stage run side by side; stages run one after another. Write pipeline_minutes(stages): stages is a list of lists of job durations in minutes. Return the total: the sum, over stages, of each stage's longest job.
def pipeline_minutes(stages): return sum(sum(stage) for stage in stages) print(pipeline_minutes([[1, 2], [8, 3, 5], [4]]))
Write jobs_to_run(changed, filters): filters maps job names to glob patterns (matched with fnmatch.fnmatch). Return the sorted names of jobs with at least one pattern that matches at least one changed path.
from fnmatch import fnmatch FILTERS = { "docs": ["docs/*", "*.md"], "api-tests": ["api/*", "requirements.txt"], "web-tests": ["web/*", "package.json"], } def jobs_to_run(changed, filters): return sorted(filters) print(jobs_to_run(["api/routes.py", "README.md"], FILTERS))
An electrician can wire a new lamp today, and you can flip the switch next week. A feature flag is that switch, in your code: if flags.enabled("new_checkout", user):. The code ships turned off, then you turn it on for staff, then 5% of users, then everyone. If something breaks, you turn it off in seconds, with no deploy.
In plain words: deploying puts the code on the servers. Releasing lets people use it. Flags let you do those at different times.
For percentage rollouts, each user must get a stable answer, like a fixed raffle number. Put the flag name and user id through a hash to get a bucket from 0 to 99, and turn the flag on when the bucket is below the percentage. Raising 5% to 20% keeps the first 5% in, and adds more. Then delete old flags: each one is a branch in your code that someone must understand.
The same user always lands in the same bucket for a given flag.
import hashlib def bucket(flag, user_id): digest = hashlib.sha256(f"{flag}:{user_id}".encode()).hexdigest() return int(digest, 16) % 100 for user in ["ana", "bo", "chen", "dev"]: b = bucket("new_checkout", user) print(user, b, "on at 25%" if b < 25 else "off at 25%") print(bucket("new_checkout", "ana") == bucket("new_checkout", "ana"))
Including the flag name means each flag gets its own mix of users, so the same people aren't always first.
bucket = 37 print([bucket < pct for pct in (10, 25, 50, 100)])
[False, False, True, True]
bucket < pct is False at 10 and 25, and True at 50 and 100, which gives [False, False, True, True]. They join once the rollout passes 37% and stay in as it grows, because the bucket never changes.
Write a sentence or two, then compare it with a good answer in the lesson.
Workflows live in .github/workflows/ as YAML:
name: ci on: pull_request: push: branches: [main] permissions: contents: read jobs: lint: runs-on: ubuntu-latest steps: - uses: actions/checkout@v7 - uses: actions/setup-python@v7 with: { python-version: "3.12", cache: pip } - run: pip install -r requirements-dev.txt - run: ruff check . && mypy src test: needs: lint runs-on: ubuntu-latest strategy: matrix: python: ["3.11", "3.12"] steps: - uses: actions/checkout@v7 - uses: actions/setup-python@v7 with: { python-version: "${{ matrix.python }}", cache: pip } - run: pip install -r requirements-dev.txt - run: pytest -q deploy: needs: test if: github.ref == 'refs/heads/main' runs-on: ubuntu-latest environment: production steps: - uses: actions/checkout@v7 - run: ./deploy.sh env: DEPLOY_TOKEN: ${{ secrets.DEPLOY_TOKEN }}
The parts: triggers (on), jobs that run on fresh machines, steps inside each job, needs for order, a matrix that runs a job once per Python version, caching of installed packages, permissions that let the workflow's token read the code and nothing more, and secrets injected only where needed. The production environment can require a person's approval.
Three habits keep a workflow safe. Give the workflow token only the permissions it needs, with a permissions: block, as above. Pin third-party actions to a full commit SHA, since a tag or a branch can move. And never print a secret: use it only in the step that needs it.
Quarantine it and give its fix an owner
The fix is still to find and remove the cause. Until that lands, quarantine takes the test out of the required checks, so a red build keeps meaning something, and the owner makes sure the fix isn't forgotten.
If you pick users at random on each request, someone may see the new checkout, then the old one, then the new one again. That's confusing for them, and it makes your data useless, since nobody had a consistent experience. Hashing the user id with the flag name, as this lesson's example does, gives each person the same answer every time. Their bucket stays the same as you widen the rollout, so people who already have the feature keep it.
Every flag adds a branch to your code, and old flags pile up. After a while, nobody knows what happens if an old one is turned off, and a stale flag has caused serious outages when someone flipped it years later. So when a rollout finishes, delete the flag and the old path. Give each flag an owner and an expected end date when you create it. Some teams add a test that fails if a flag is past its date, which keeps the cleanup from being forgotten.
Add continuous integration to one of your own repositories: a workflow file that runs your tests on every push and pull request, so a broken change shows a red cross before anyone merges it.
Write it at .github/workflows/tests.yml, push, and watch the run on GitHub's Actions tab. Paste the file into the starter for a quick check, then ask the tutor to review it.
WORKFLOW = '''name: tests on: push: branches: [main] pull_request: jobs: test: runs-on: ubuntu-latest steps: - uses: actions/checkout@v7 - uses: actions/setup-python@v7 with: python-version: "3.12" - run: pip install -r requirements.txt - run: pytest -q ''' def check(text): problems = [] if "pull_request" not in text: problems.append("Run on pull requests too, so problems show before merging") if "push" not in text: problems.append("Run on pushes") if "actions/checkout" not in text: problems.append("Check out the code first (actions/checkout)") if "setup-python" not in text or "python-version" not in text: problems.append("Set up a pinned Python version " "(actions/setup-python with python-version)") if "pytest" not in text: problems.append("Run pytest") if "|| true" in text: problems.append("'|| true' hides failures: let a failing test fail the job") return problems DONE = "Looks right. Push it, break a test on purpose, and watch it go red, then green." for p in check(WORKFLOW) or [DONE]: print("-", p)
The pipeline skips the jobs the change can't affect
A path filter starts a job only when files it depends on changed. A docs-only change doesn't need the ten-minute build, so the pipeline answers sooner and costs less.
Write a sentence or two, then compare it with a good answer in the lesson.
Start with a short baseline or choose guided, independent, or AI-assisted practice.
What's the difference between continuous delivery and continuous deployment?
575 lessons in thirteen phases. 176 are free without an account, and a free account opens the rest. See every lesson.
Go from your first line of code to working as a Python developer: projects, testing, data, databases, web apps and APIs, all in your browser.
Design, test, deploy, and operate an HTTP API that another engineer can use.
Never trained an AI? Teach a small one to write, right in your browser. It takes about 20 seconds and needs no account. Teach it to write