Cloud and DevOps
CI/CD with GitHub Actions
These notes take a small Python bank service from a first lint-and-test workflow to a matrix build, a container image and an approved production deploy, mostly in diagrams and tables. Every command the workflows call was run locally and its output is pasted; the workflow files themselves were linted but not executed on GitHub.
The idea
Part 1 of 6 · what a pipeline is and what it buys you
The pipeline in one picture
CI/CD is one automated path from a commit to a running service. Each stage is a gate: if it fails, nothing after it runs.
How this page was checked: no workflow here was executed on GitHub, so the page shows no run logs or durations. Each YAML file was parsed with PyYAML and passed actionlint 1.7.12, and every shell command inside them was run locally against the project below.
Integration, delivery, deployment
Three terms share the letters. The difference is how far the automation goes and who presses the last button.
| Term | Automated up to | Release to production | You need first |
|---|---|---|---|
| Continuous integration | Build and test on every push | Not covered | Fast, trusted tests |
| Continuous delivery | A deployable artifact, staged | One human click | Repeatable deploy script |
| Continuous deployment | Production | Automatic on green | Monitoring, rollback, feature flags |
Interview point: most teams that say "CD" mean delivery. Full deployment is a statement about your tests and rollback, not about your YAML.
What a red pipeline protects you from
A step fails when its command exits non-zero. Here a copy of the project has an unused import and a removed balance check, and both tools say so with exit code 1.
- Broken code never reaches the shared branch, so nobody else pulls it.
- "Works on my machine" is replaced by one clean machine everyone trusts.
- Review time goes to design, because style and regressions are already checked.
The GitHub Actions model
Part 2 of 6 · six nouns, one folder, a first workflow
Event, workflow, job, step, runner, action
An event starts a workflow, a workflow is a set of jobs, and each job is a list of steps on its own runner.
| Noun | What it is | Trap |
|---|---|---|
| Event | Something that happened: push, pull request, timer, button | One event can start many workflows |
| Workflow | One YAML file | Must be under .github/workflows/ |
| Job | Steps that run on one runner | Jobs run in parallel unless needs says otherwise |
| Step | run: a shell command or uses: an action | Each run is a new shell: cd does not carry over |
| Runner | The machine: GitHub-hosted VM or your own | Hosted runners start empty every job |
| Action | A packaged step from another repository | It is third-party code running with your token |
What a push sets off
GitHub matches the event against every workflow file at that commit, then hands each job to a free runner.
Note: the workflow file is read from the commit that triggered the run, so a branch can change its own pipeline. That is why the fork rules exist.
Anatomy of a workflow file
Three top-level keys do the work: name, on and jobs. The last step below is an ordinary shell command, run locally underneath.
| Path | Holds |
|---|---|
.github/workflows/*.yml | Workflows. Subfolders are not scanned. |
.github/actions/<name>/action.yml | Your own composite actions (a convention, any path works) |
| Repository settings | Secrets, variables, environments, branch rules |
The project and its local run
The service is a small bank module (deposit, withdraw, transfer, balances in whole rupees) with six pytest cases and a stdlib HTTP app. A pipeline only automates commands, so they must pass on your machine first.
See also: the tools themselves are covered in Testing with pytest and Code quality.
A first CI workflow
The same four commands, on a clean Ubuntu VM, for every push to main and every pull request.
| Step | Does | Why |
|---|---|---|
actions/checkout | Clones the commit into the workspace | The runner starts with no code |
actions/setup-python | Puts the chosen Python on PATH | Pin the version, do not take the VM default |
cache: pip | Restores pip's download cache, keyed on the requirements file | Skips downloads, still runs pip install |
ruff check, ruff format --check | Lint and formatting, read-only | Cheapest check goes first |
pytest --cov-fail-under=90 | Tests, and fails under 90% coverage | The gate is the exit code |
Versions: action majors on this page were checked against the public release list on 24 Nov 2026: actions/checkout v7, actions/setup-python v7, actions/cache v6, actions/upload-artifact v7, docker/login-action v4, docker/build-push-action v7, aws-actions/configure-aws-credentials v6. They move about once a year, so check before copying.
Triggers and jobs
Part 3 of 6 · when a run starts and how its jobs are arranged
Triggers and filters
The on key lists events, and each event can be narrowed by branch and by changed paths.
| Trigger | Fires when | Trap |
|---|---|---|
push | Commits or tags land on a matching ref | Without a branch filter it also runs on every feature branch, doubling pull request runs |
pull_request | A pull request is opened, updated or reopened | branches filters the target branch, not the source |
schedule | Cron, in UTC | Runs only from the default branch, and can start late under load |
workflow_dispatch | Someone presses "Run workflow" or calls the API | The file must exist on the default branch to show the button |
paths / paths-ignore | The diff touches (or only touches) matching files | A skipped workflow that is a required check stays pending forever |
Trap: never paste ${{ github.event.* }} text into a run: line, because a pull request title can then inject shell. Pass it through env: as above.
pull_request versus pull_request_target
A fork's pull request is untrusted code. pull_request runs it with nothing worth stealing; pull_request_target runs your trusted workflow with secrets, and becomes dangerous the moment it checks out the fork's code.
- Use
pull_requestfor build and test. It is the safe default. - Use
pull_request_targetonly for work that needs no fork code: labels, comments, triage. - Pull requests from branches of the same repository are trusted and do get secrets.
Job order with needs
Jobs run in parallel by default. needs draws the edges of the graph, and a failed job skips everything downstream.
Trap: a skipped job also skips its dependants. A cleanup or notify job that must always run needs if: always().
Matrix builds
A matrix copies one job once per value, each copy on its own runner. Locally the same suite was run on the two interpreters available here (3.9 and 3.13; 3.11 was not run).
needs: test waits for all three.fail-fast: true(the default) cancels the other copies on the first failure. Setfalseto see which versions really fail.- Two keys multiply: 3 Pythons by 2 operating systems is 6 jobs and 6 times the minutes.
- Artifact names must be unique per copy, hence
junit-${{ matrix.python }}.
Concurrency, timeouts, conditionals
Three small keys stop a pipeline wasting minutes or deploying out of order.
| Key | Effect | Typical use |
|---|---|---|
concurrency.group + cancel-in-progress: true | A new run in the same group cancels the old one | Pull requests: only the latest push matters |
concurrency.group, cancel off | Runs in the group queue one at a time | Deploys: never two at once, never cancel halfway |
timeout-minutes | Kills the job after N minutes (default 360) | A hung test should cost 10 minutes, not 6 hours |
if: | Skips a job or step unless the expression is true | github.ref == 'refs/heads/main', always(), failure() |
continue-on-error: true | A failure does not fail the job | Experimental checks only: it hides real failures |
Speed and security
Part 4 of 6 · shorter runs, and nothing worth stealing in them
Caching and cache keys
A cache is a folder saved under a key and restored by a later run. Put a hash of the lock or requirements file in the key, so the cache changes exactly when the dependencies do.
restore-keys gives the prefix fallback; an exact hit is never overwritten.| Safe to cache | Do not cache |
|---|---|
Package manager downloads (~/.cache/pip, Go module cache) | Anything containing secrets or tokens |
| Docker build layers | Test results or build outputs you then trust as fresh |
Tool caches (.ruff_cache, .mypy_cache) | A virtualenv keyed without the Python version |
Limits (approximate): a branch can read caches from its base branch but not from sibling branches, unused entries expire after about a week, and each repository has a size cap of around 10 GB.
Artifacts, splitting, running only what changed
A cache is a speed-up you can lose. An artifact is an output you mean to keep or hand to another job.
| Cache | Artifact | |
|---|---|---|
| Purpose | Reuse downloads between runs | Keep or pass on a result of this run |
| Addressed by | Key you compute | Name, within one run |
| If missing | Run is slower, still correct | Downstream job fails |
| Lifetime | Evicted when unused or over quota | Retention days (90 by default) |
| Examples | pip cache, Docker layers | JUnit report, coverage HTML, wheel |
| Speed-up | How | Cost |
|---|---|---|
| Split tests | A matrix of shards, each running a slice of the suite | More runners; needs tests with no shared state |
| Only what changed | paths filters, or a first job that diffs and sets outputs | Missed dependencies between folders |
| Cancel stale runs | concurrency with cancel-in-progress | None on pull requests |
| Order by cost | Lint before tests, unit before integration | None |
Secrets and variables
Secrets are encrypted, write-only and masked in logs; variables are plain configuration. Both exist at organisation, repository and environment level, and the narrowest scope wins.
secrets.NAME | vars.NAME | |
|---|---|---|
| Readable in the UI later | No | Yes |
| Masked in logs | Yes, exact string only | No |
| Use for | Tokens, passwords, signing keys | URLs, region names, role ARNs, flags |
- Never
echoa secret: masking misses any transformed form, such as base64 or one character per line. - Pass secrets through
env:on the one step that needs them, not at workflow level. GITHUB_TOKENis created per job and expires when the job ends. Prefer it to a personal token.
Least privilege and pinned actions
An action is someone else's code running with your token. Give the token almost nothing, and pin the code to a commit that cannot be moved.
| Reference | Can it change under you? | Use for |
|---|---|---|
@v7 | Yes: the tag moves with every release | First-party actions, if you accept the risk |
@v7.0.1 | Yes: a tag can be re-pointed | Rarely the right choice |
@3d3c42e... (full SHA) | No | Third-party actions, and anything touching secrets |
Note: the SHA above is the commit that actions/checkout tag v7.0.1 pointed to on 24 Nov 2026. Keep the version in a trailing comment so an update bot can bump both.
OIDC instead of stored cloud keys
A long-lived access key in a secret can leak and works from anywhere. With OIDC the job proves who it is with a signed token, and the cloud hands back credentials that last minutes.
Interview point: the security is in the cloud role's trust policy. It must match the token's sub claim (repository plus branch or environment), or any repository on GitHub could assume the role.
What an untrusted pull request can reach
Assume a fork's author controls every file in the checkout, including test code and build scripts.
| Resource | Fork pull request (pull_request) | Same-repository branch |
|---|---|---|
| Repository secrets | No | Yes |
GITHUB_TOKEN | Read-only | As set by permissions |
| OIDC token | No (id-token: write is not granted) | Yes, if requested |
| Environment secrets | No | Only after the environment's rules pass |
| Caches | Read base branch caches, write only its own | Read and write |
| Hosted runner | Yes, optionally after a maintainer approves the run | Yes |
Trap: workflows triggered by workflow_run or pull_request_target run trusted, so an artifact or branch name produced by the fork is attacker input there too.
Build and deliver
Part 5 of 6 · from a green commit to a running service
Build and publish an image
Build once per commit, tag with the commit SHA, push to a registry. The build below is a real local run; the push needs a registry and was not run.
Tag (:3f9c2ab, :latest) | Digest (@sha256:d6a3...) | |
|---|---|---|
| Is | A movable name | A hash of the image content |
| Can be re-pointed | Yes | No |
| Use for | Finding an image by commit | What you deploy and promote |
Seen in this run: rebuilding the same source a minute later produced a different digest (sha256:33c6...), because build metadata is part of the image: build once and promote that digest. Layers and multi-stage builds are in the Docker notes.
Environments and promotion
One image digest moves through environments; only configuration differs. A GitHub environment is a named target with its own secrets, variables and protection rules.
| Environment rule | Effect |
|---|---|
| Required reviewers | The job waits until a named person approves: the manual gate |
| Wait timer | A fixed delay before the job starts |
| Deployment branches | Only main (or tags) may deploy here |
| Environment secrets | Released to the job only after the rules pass |
Note: a job opts in with environment: production. Which rules are available depends on the plan and on whether the repository is public.
Deployment strategies and rollback
The strategy decides how many users see a bad release and how fast you can undo it.
| Strategy | In one line | Rollback |
|---|---|---|
| Recreate | Stop the old version, start the new: downtime | Redeploy the old image |
| Rolling | Replace instances a few at a time | Roll back the same way, slowly |
| Blue-green | Run both, switch all traffic at once | Switch back: seconds |
| Canary | Send a small share of traffic, watch metrics, widen | Send the share back to old |
| Feature flag | Ship the code dark, turn it on later | Turn the flag off, no deploy |
- Rollback means deploying the previous digest with the same pipeline, not a special script nobody has tested.
- Rolling back code is easy; rolling back data is not, which is the next chapter.
Database migrations in a pipeline
During a deploy, old and new code run against one database at the same time. So every schema change is split into steps that are each safe for both versions: expand, then contract.
| Step | Example: rename balance to balance_rupees |
|---|---|
| Expand | Add the new nullable column. Old code ignores it. |
| Dual write | Deploy code that writes both columns, reads the old one |
| Backfill | Copy old rows in batches, outside the deploy job |
| Switch reads | Deploy code that reads the new column |
| Contract | Drop the old column once no running version uses it |
Rule: run migrations as their own job before the deploy job, with a timeout and a concurrency group so two never run together.
Smoke tests after deploy
A deploy that "succeeded" only proves the command returned. A smoke test asks the running service one or two cheap questions and fails the job if the answer is wrong.
curl -fturns an HTTP error into a non-zero exit, which is what fails the step.- Return the version from
/healthand compare it with the commit SHA, so you know the new build is the one answering. - Smoke tests check "is it up"; they do not replace the test suite.
Reuse, upkeep and reference
Part 6 of 6 · keeping many pipelines small, green and cheap
Reusable workflows and composite actions
Two ways to stop copying YAML: share a list of steps, or share whole jobs.
| Composite action | Reusable workflow | |
|---|---|---|
| Shares | Steps | Whole jobs |
| Called from | A step: uses: ./.github/actions/x | A job: uses: ./.github/workflows/x.yml |
| Runner | The caller's | Its own |
| Secrets, environments | Only what the caller passes as inputs | Yes: secrets: and environment: |
| Reach for it when | The same setup steps repeat in many jobs | Teams should share one deploy or release process |
Required checks, flaky tests, cost
A pipeline only protects main if merging without it is impossible. Branch protection (or a ruleset) makes named checks required; pull request flow itself is in Git in depth.
| Topic | Do | Avoid |
|---|---|---|
| Required checks | Require the job names that gate quality, and "up to date with base" | Requiring a path-filtered workflow that may never start |
| Flaky tests | Quarantine, open a ticket, fix the shared state or timing | A habit of "re-run until green": it trains people to ignore red |
| Cost | Cancel stale runs, cache, set timeouts, prefer Linux runners | Wide matrices on every push; macOS and Windows minutes cost a multiple of Linux |
- Hosted runner minutes are metered for private repositories and the rates change, so check the current pricing page.
- Self-hosted runners give you your own hardware and network access, and make patching and isolation your job.
- Never attach a self-hosted runner to a public repository: a fork's pull request would run its code on your machine.
Reading a failed run
Start at the first failing step of the first failing job. Everything after it is usually noise.
- Read the last 20 lines of the failed step, then the exit code, before scrolling up.
- Print tool versions in an early step, so the log answers "which Python, which ruff".
- Upload reports with
if: always(), asjobs.ymldoes, so a failure leaves evidence.
A complete reference workflow
Everything above in one file: lint, a test matrix, an image pushed by digest, staging, then production behind an approval. It uses the composite action and the reusable workflow from two chapters back.
main builds and deploys.Limits of that check: actionlint validates syntax, expressions and known action inputs. It ran without shellcheck and outside a Git repository, and it cannot tell you whether a deploy works.
Syntax cheat sheet
| Need | Syntax |
|---|---|
| Run on push to main and on pull requests | on: {push: {branches: [main]}, pull_request: {}} |
| Manual button | on: workflow_dispatch |
| Nightly | on: {schedule: [{cron: "30 2 * * *"}]} (UTC) |
| Job order | needs: [lint, test] |
| Matrix | strategy: {matrix: {python: ["3.9", "3.13"]}}, read as ${{ matrix.python }} |
| Cancel stale runs | concurrency: {group: ..., cancel-in-progress: true} |
| Only on main | if: github.ref == 'refs/heads/main' |
| Run even after failure | if: always() |
| Step output | echo "name=value" >> "$GITHUB_OUTPUT", read as steps.<id>.outputs.name |
| Job output | outputs: {ref: ...}, read as needs.<job>.outputs.ref |
| Secret, variable | ${{ secrets.NAME }}, ${{ vars.NAME }} |
| Token scope | permissions: {contents: read} |
| Approval gate | environment: production plus required reviewers in settings |
| Call a reusable workflow | Job-level uses: ./.github/workflows/x.yml with with: and secrets: |
Interview questions
| Question | Short answer |
|---|---|
| Continuous delivery or deployment? | Delivery stops at a deployable artifact and a human click. Deployment releases every green commit automatically. |
| Why build the image once? | A rebuild is a different artifact (different digest). What you tested must be byte-for-byte what you ship. |
| How do you run CI safely on fork pull requests? | pull_request: read-only token and no secrets. Never check out fork code under pull_request_target. |
| How does a job get cloud access without stored keys? | OIDC: a signed token per job, exchanged for short-lived credentials by a role whose trust policy pins the repository and environment. |
| Cache or artifact? | Cache is an optional speed-up keyed by a hash. An artifact is a named output of one run that other jobs or people need. |
| The pipeline takes 25 minutes. What do you do? | Measure per job, then cache dependencies, order by cost, split tests across a matrix, cancel stale runs, and run only what changed. |
| How do you change a column with zero downtime? | Expand, dual write, backfill, switch reads, contract: each release works with the schema before and after it. |
| A test fails one run in ten. What now? | Treat it as a bug: quarantine it, find the shared state or timing, fix it. Automatic retries hide real failures. |
Back to Cloud and DevOps.