Learnings

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

The idea

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.

The same steps, in the same order, for every commit.

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

The idea

Three terms share the letters. The difference is how far the automation goes and who presses the last button.

TermAutomated up toRelease to productionYou need first
Continuous integrationBuild and test on every pushNot coveredFast, trusted tests
Continuous deliveryA deployable artifact, stagedOne human clickRepeatable deploy script
Continuous deploymentProductionAutomatic on greenMonitoring, 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

The idea

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

The GitHub Actions model

An event starts a workflow, a workflow is a set of jobs, and each job is a list of steps on its own runner.

Jobs are isolated from each other; steps in one job share a disk.
NounWhat it isTrap
EventSomething that happened: push, pull request, timer, buttonOne event can start many workflows
WorkflowOne YAML fileMust be under .github/workflows/
JobSteps that run on one runnerJobs run in parallel unless needs says otherwise
Steprun: a shell command or uses: an actionEach run is a new shell: cd does not carry over
RunnerThe machine: GitHub-hosted VM or your ownHosted runners start empty every job
ActionA packaged step from another repositoryIt is third-party code running with your token

What a push sets off

The GitHub Actions model

GitHub matches the event against every workflow file at that commit, then hands each job to a free runner.

The result is a check attached to the commit, which pull requests display.

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

The GitHub Actions model

Three top-level keys do the work: name, on and jobs. The last step below is an ordinary shell command, run locally underneath.

PathHolds
.github/workflows/*.ymlWorkflows. Subfolders are not scanned.
.github/actions/<name>/action.ymlYour own composite actions (a convention, any path works)
Repository settingsSecrets, variables, environments, branch rules

The project and its local run

The GitHub Actions model

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 GitHub Actions model

The same four commands, on a clean Ubuntu VM, for every push to main and every pull request.

StepDoesWhy
actions/checkoutClones the commit into the workspaceThe runner starts with no code
actions/setup-pythonPuts the chosen Python on PATHPin the version, do not take the VM default
cache: pipRestores pip's download cache, keyed on the requirements fileSkips downloads, still runs pip install
ruff check, ruff format --checkLint and formatting, read-onlyCheapest check goes first
pytest --cov-fail-under=90Tests, and fails under 90% coverageThe 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

Triggers and jobs

The on key lists events, and each event can be narrowed by branch and by changed paths.

TriggerFires whenTrap
pushCommits or tags land on a matching refWithout a branch filter it also runs on every feature branch, doubling pull request runs
pull_requestA pull request is opened, updated or reopenedbranches filters the target branch, not the source
scheduleCron, in UTCRuns only from the default branch, and can start late under load
workflow_dispatchSomeone presses "Run workflow" or calls the APIThe file must exist on the default branch to show the button
paths / paths-ignoreThe diff touches (or only touches) matching filesA 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

Triggers and jobs

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.

Same event, two trust levels.
  • Use pull_request for build and test. It is the safe default.
  • Use pull_request_target only 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

Triggers and jobs

Jobs run in parallel by default. needs draws the edges of the graph, and a failed job skips everything downstream.

Cheap jobs first, so a typo costs seconds and not a full test run.

Trap: a skipped job also skips its dependants. A cleanup or notify job that must always run needs if: always().

Matrix builds

Triggers and jobs

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).

Fan out to test, fan in before build: needs: test waits for all three.
  • fail-fast: true (the default) cancels the other copies on the first failure. Set false to 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

Triggers and jobs

Three small keys stop a pipeline wasting minutes or deploying out of order.

Life of one job.
KeyEffectTypical use
concurrency.group + cancel-in-progress: trueA new run in the same group cancels the old onePull requests: only the latest push matters
concurrency.group, cancel offRuns in the group queue one at a timeDeploys: never two at once, never cancel halfway
timeout-minutesKills 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 truegithub.ref == 'refs/heads/main', always(), failure()
continue-on-error: trueA failure does not fail the jobExperimental 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

Speed and security

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 cacheDo not cache
Package manager downloads (~/.cache/pip, Go module cache)Anything containing secrets or tokens
Docker build layersTest 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

Speed and security

A cache is a speed-up you can lose. An artifact is an output you mean to keep or hand to another job.

CacheArtifact
PurposeReuse downloads between runsKeep or pass on a result of this run
Addressed byKey you computeName, within one run
If missingRun is slower, still correctDownstream job fails
LifetimeEvicted when unused or over quotaRetention days (90 by default)
Examplespip cache, Docker layersJUnit report, coverage HTML, wheel
Speed-upHowCost
Split testsA matrix of shards, each running a slice of the suiteMore runners; needs tests with no shared state
Only what changedpaths filters, or a first job that diffs and sets outputsMissed dependencies between folders
Cancel stale runsconcurrency with cancel-in-progressNone on pull requests
Order by costLint before tests, unit before integrationNone

Secrets and variables

Speed and security

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.NAMEvars.NAME
Readable in the UI laterNoYes
Masked in logsYes, exact string onlyNo
Use forTokens, passwords, signing keysURLs, region names, role ARNs, flags
  • Never echo a 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_TOKEN is created per job and expires when the job ends. Prefer it to a personal token.

Least privilege and pinned actions

Speed and security

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.

ReferenceCan it change under you?Use for
@v7Yes: the tag moves with every releaseFirst-party actions, if you accept the risk
@v7.0.1Yes: a tag can be re-pointedRarely the right choice
@3d3c42e... (full SHA)NoThird-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

Speed and security

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.

Nothing secret is stored in GitHub at all.

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

Speed and security

Assume a fork's author controls every file in the checkout, including test code and build scripts.

ResourceFork pull request (pull_request)Same-repository branch
Repository secretsNoYes
GITHUB_TOKENRead-onlyAs set by permissions
OIDC tokenNo (id-token: write is not granted)Yes, if requested
Environment secretsNoOnly after the environment's rules pass
CachesRead base branch caches, write only its ownRead and write
Hosted runnerYes, optionally after a maintainer approves the runYes

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 and deliver

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...)
IsA movable nameA hash of the image content
Can be re-pointedYesNo
Use forFinding an image by commitWhat 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

Build and deliver

One image digest moves through environments; only configuration differs. A GitHub environment is a named target with its own secrets, variables and protection rules.

Promotion moves the same artifact forward; it never rebuilds.
Environment ruleEffect
Required reviewersThe job waits until a named person approves: the manual gate
Wait timerA fixed delay before the job starts
Deployment branchesOnly main (or tags) may deploy here
Environment secretsReleased 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

Build and deliver

The strategy decides how many users see a bad release and how fast you can undo it.

StrategyIn one lineRollback
RecreateStop the old version, start the new: downtimeRedeploy the old image
RollingReplace instances a few at a timeRoll back the same way, slowly
Blue-greenRun both, switch all traffic at onceSwitch back: seconds
CanarySend a small share of traffic, watch metrics, widenSend the share back to old
Feature flagShip the code dark, turn it on laterTurn 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

Build and deliver

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.

Renaming a column takes several releases, and each one can be rolled back.
StepExample: rename balance to balance_rupees
ExpandAdd the new nullable column. Old code ignores it.
Dual writeDeploy code that writes both columns, reads the old one
BackfillCopy old rows in batches, outside the deploy job
Switch readsDeploy code that reads the new column
ContractDrop 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

Build and deliver

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 -f turns an HTTP error into a non-zero exit, which is what fails the step.
  • Return the version from /health and 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

Reuse, upkeep and reference

Two ways to stop copying YAML: share a list of steps, or share whole jobs.

Composite actionReusable workflow
SharesStepsWhole jobs
Called fromA step: uses: ./.github/actions/xA job: uses: ./.github/workflows/x.yml
RunnerThe caller'sIts own
Secrets, environmentsOnly what the caller passes as inputsYes: secrets: and environment:
Reach for it whenThe same setup steps repeat in many jobsTeams should share one deploy or release process

Required checks, flaky tests, cost

Reuse, upkeep and reference

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.

TopicDoAvoid
Required checksRequire the job names that gate quality, and "up to date with base"Requiring a path-filtered workflow that may never start
Flaky testsQuarantine, open a ticket, fix the shared state or timingA habit of "re-run until green": it trains people to ignore red
CostCancel stale runs, cache, set timeouts, prefer Linux runnersWide 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

Reuse, upkeep and reference

Start at the first failing step of the first failing job. Everything after it is usually noise.

"Passes locally, fails in CI" is almost always a version, a missing secret or a stale cache.
  • 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(), as jobs.yml does, so a failure leaves evidence.

A complete reference workflow

Reuse, upkeep and reference

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.

Pull requests get lint and tests; only a push to 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

Reuse, upkeep and reference

NeedSyntax
Run on push to main and on pull requestson: {push: {branches: [main]}, pull_request: {}}
Manual buttonon: workflow_dispatch
Nightlyon: {schedule: [{cron: "30 2 * * *"}]} (UTC)
Job orderneeds: [lint, test]
Matrixstrategy: {matrix: {python: ["3.9", "3.13"]}}, read as ${{ matrix.python }}
Cancel stale runsconcurrency: {group: ..., cancel-in-progress: true}
Only on mainif: github.ref == 'refs/heads/main'
Run even after failureif: always()
Step outputecho "name=value" >> "$GITHUB_OUTPUT", read as steps.<id>.outputs.name
Job outputoutputs: {ref: ...}, read as needs.<job>.outputs.ref
Secret, variable${{ secrets.NAME }}, ${{ vars.NAME }}
Token scopepermissions: {contents: read}
Approval gateenvironment: production plus required reviewers in settings
Call a reusable workflowJob-level uses: ./.github/workflows/x.yml with with: and secrets:

Interview questions

Reuse, upkeep and reference

QuestionShort 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.