Skip to lesson

Practice: GitHub Actions

A review of this module. Skip it if you feel confident; the next module does not need it.

Fix the mistakes

The slips that cost marks in this module. Spot each one, then check the fix.

Workflows usually break in a few familiar ways: invalid YAML, a trigger that never fires, a missing checkout or permission, or a leaked secret. Can you spot each one in the file and in the log?

Five bugs in one workflow

This workflow has five bugs. Find each one, then compare with the fixed version below it.

Example 1 · The broken workflow and the fixed one

Runs in: a GitHub repository with the shoplite-api project

YAML
# BROKENname: CIon:  push:    branches: [master]                       # bug 2: the branch is mainjobs:  build:    runs-on: ubuntu-latest    steps:      - uses: actions/setup-java@v5           # bug 3: no checkout before it        with:          distribution: temurin          java-version: '25'      - run: ./mvnw -B verify      - run: echo "token ${{ secrets.GHCR_TOKEN }}" | base64   # bug 5: secret printed      - uses: docker/login-action@v3          # bug 4: no packages: write        with:          registry: ghcr.io          username: ${{ github.actor }}          password: ${{ secrets.GITHUB_TOKEN }}      - uses: docker/build-push-action@v6        with:        push: true                            # bug 1: not indented under with# FIXEDname: CIon:  push:    branches: [main]  pull_request:    branches: [main]jobs:  build:    runs-on: ubuntu-latest    permissions:      contents: read      packages: write    steps:      - uses: actions/checkout@v5      - uses: actions/setup-java@v5        with:          distribution: temurin          java-version: '25'          cache: maven      - run: ./mvnw -B verify      - uses: docker/login-action@v3        with:          registry: ghcr.io          username: ${{ github.actor }}          password: ${{ secrets.GITHUB_TOKEN }}      - uses: docker/build-push-action@v6        with:          push: true          tags: ghcr.io/${{ github.repository_owner }}/shoplite-api:sha-${{ github.sha }}
Sample output
(broken) Invalid workflow file: .github/workflows/ci.yml#L23
         You have an error in your yaml syntax on line 23
(fixed)  build ✓  pushed ghcr.io/asha-rao/shoplite-api:sha-4e1c9a7d0b2f63a8c5e94d1f07a2b6c3e8d9f012

What this code does

  • Only bug 1 is reported at once; after fixing it, bug 2 means nothing runs on main, bug 3 fails with ./mvnw: No such file or directory, bug 4 fails the push, and bug 5 never fails but leaks a token that must be rotated.
  • The fixed file still pushes from every event in one job; the next example splits it so pull requests never push.

Check a workflow in this order. Is the YAML valid? Does on: match your branch names? Does every job start with actions/checkout? Does the image job have permissions: packages: write? Does any step print a secret?

The first two stop the workflow from starting at all; the next two fail a step with a clear message; the last one fails nothing and leaks quietly, which makes it the most dangerous.

Find the bug

Find the workflow bug

Tap the line that causes the problem.

Nothing runs when you push to main. Which line is the problem?

Round 1 of 3

Adding caching and predicting hits

This program predicts the Maven cache result for five runs in one week. Guess each line before you read the output.

Example 2 · Predicting cache hits over a week

CacheWeekDemo.javaJava
import java.util.HashSet;import java.util.List;import java.util.Set;
public class CacheWeekDemo {    record Run(String day, String branch, String pomVersion) {}
    public static void main(String[] args) {        Set<String> mainCaches = new HashSet<>();        List<Run> runs = List.of(                new Run("Mon", "main", "pom-v1"),                new Run("Tue", "feature/coupons", "pom-v1"),                new Run("Wed", "main", "pom-v1"),                new Run("Thu", "feature/testcontainers", "pom-v2"),                new Run("Fri", "main", "pom-v2"));
        for (Run r : runs) {            String key = "Linux-maven-" + r.pomVersion();            String result;            if (mainCaches.contains(key)) {                result = "exact hit";            } else if (!mainCaches.isEmpty()) {                result = "partial hit, saves " + key;            } else {                result = "miss, saves " + key;            }            if (r.branch().equals("main")) {                mainCaches.add(key);          // caches saved on main are visible to every branch            }            System.out.printf("%s %-23s %s%n", r.day(), r.branch(), result);        }    }}
Output
Mon main                    miss, saves Linux-maven-pom-v1
Tue feature/coupons         exact hit
Wed main                    exact hit
Thu feature/testcontainers  partial hit, saves Linux-maven-pom-v2
Fri main                    partial hit, saves Linux-maven-pom-v2

What this code does

  • Tuesday's branch reads Monday's main cache, an exact hit. Thursday's branch changed the pom, so it gets a partial hit through restore-keys and saves a cache for itself only.
  • Friday's main cannot see Thursday's branch cache (branches do not share with each other or with main), so main pays the partial hit once more and then every branch can use pom-v2. A simplified model of GitHub's scope rules.

Add cache: maven to actions/setup-java. The key changes only when a pom.xml changes, so the first run after a dependency change misses (or partially hits) and saves; every following run with the same pom is an exact hit.

Caches are per branch, and a pull request can read main's cache. So a new feature branch usually starts with a hit from main, as long as its pom is unchanged.

Predict the output

Hit, partial hit or miss?

main already saved the cache Linux-maven-pom-v1.

Round 1 of 3

A new feature branch runs for the first time, with an unchanged pom.xml. What happens?

branch: feature/coupons
key: Linux-maven-pom-v1
restore-keys: Linux-maven-

Splitting one job into build-test and image

Least privilege means each job gets only the permissions it needs. Here build-test can only read the code, and only the image job may write packages.

One long job that tests and pushes mixes two concerns. This workflow splits them into two jobs with different rights.

Example 3 · One job split into build-test and image

Runs in: a GitHub repository with the shoplite-api project

YAML
jobs:  build-test:                                   # runs on PRs and pushes, read-only    runs-on: ubuntu-latest    permissions:      contents: read    steps:      - uses: actions/checkout@v5      - uses: actions/setup-java@v5        with:          distribution: temurin          java-version: '25'          cache: maven      - run: ./mvnw -B verify  image:    needs: build-test                           # only after green tests    if: github.event_name == 'push' && github.ref == 'refs/heads/main'    runs-on: ubuntu-latest    permissions:      contents: read      packages: write                           # only this job can push    steps:      - uses: actions/checkout@v5      - uses: docker/setup-buildx-action@v3      - uses: docker/login-action@v3        with:          registry: ghcr.io          username: ${{ github.actor }}          password: ${{ secrets.GITHUB_TOKEN }}      - uses: docker/build-push-action@v6        with:          push: true          tags: ghcr.io/${{ github.repository_owner }}/shoplite-api:sha-${{ github.sha }}          cache-from: type=gha          cache-to: type=gha,mode=max
Sample output
(pull request #46)
build-test  ✓ 4m 05s
image       skipped

(push to main)
build-test  ✓ 4m 11s
image       ✓ 1m 02s

What this code does

  • On a pull request image is skipped by its if:, so no image and no write permission are involved; on main it runs only after build-test succeeds.
  • This version skips the image build on PRs entirely; the project lesson builds it on PRs too (without pushing), so Dockerfile mistakes are caught before merge.

build-test runs on every pull request and push with read-only rights. image has needs: build-test, its own packages: write permission and pushes only on main. The required check stays build-test.

A red test never reaches the image steps, and test code from a pull request never runs with the right to publish.

Fix the error

Connect the two jobs

Choose the line that replaces the broken one.

GitHub rejects the workflow. Which line replaces line 2?

image:
needs: build
runs-on: ubuntu-latest

Error

Job 'image' depends on unknown job 'build'.

Reading a failed run

This program names the cause from the first real error line, the habit that fixes most red runs.

Example 4 · Naming the cause from the first error line

RunLogDiagnosisDemo.javaJava
import java.util.LinkedHashMap;import java.util.List;import java.util.Map;
public class RunLogDiagnosisDemo {    static final Map<String, String> CAUSES = new LinkedHashMap<>();
    static {        CAUSES.put("Invalid workflow file", "YAML error in the workflow");        CAUSES.put("Unable to resolve action", "wrong action name or version");        CAUSES.put("Permission denied", "mvnw is not executable in Git");        CAUSES.put("There are test failures", "a test failed: read the Results block");        CAUSES.put("Could not find a valid Docker environment", "runner without Docker");        CAUSES.put("permission_denied: write_package", "missing packages: write");    }
    static String diagnose(String line) {        for (Map.Entry<String, String> e : CAUSES.entrySet()) {            if (line.contains(e.getKey())) {                return e.getValue();            }        }        return "read the full step log";    }
    public static void main(String[] args) {        List<String> firstErrors = List.of(                "/home/runner/work/_temp/1a2b.sh: line 1: ./mvnw: Permission denied",                "[ERROR] Failed to execute goal ...failsafe-plugin:3.5.6:verify ... There are test failures.",                "ERROR: failed to push ghcr.io/asha-rao/shoplite-api:sha-4e1c9a7: denied: permission_denied: write_package",                "java.lang.IllegalStateException: Could not find a valid Docker environment. Please see logs and check configuration");        for (String line : firstErrors) {            System.out.println(diagnose(line));        }    }}
Output
mvnw is not executable in Git
a test failed: read the Results block
missing packages: write
runner without Docker

What this code does

  • Each message names its cause precisely; the skill is finding the first real error line rather than the last generic one (Process completed with exit code 1).
  • The map keeps a fixed order, so a line matching several patterns gets the more specific cause first. A real log needs a human; this is a model of the habit.

Open the red job, then the first red step; read from its last lines upwards to the first clear error. The message names the class of problem:

  • Invalid workflow file / Unable to resolve action: the workflow itself.
  • Permission denied with exit 126: a file mode (mvnw).
  • [ERROR] Failures: / There are test failures: a test; the Results block names it.
  • Could not find a valid Docker environment: wrong runner for Testcontainers.
  • denied or permission_denied when pushing: missing packages: write or a login.

Predict the output

Name the cause

Read the first real error line, then pick the cause.

Round 1 of 3

What is the cause?

/home/runner/work/_temp/1a2b.sh: line 1: ./mvnw: Permission denied
Error: Process completed with exit code 126.
When in doubt, reproduce locally with the same command the step ran.

Interview drill: CI vs CD and the pull request pipeline

Practise both answers in about a minute.

  • CI vs CD: CI builds and tests every push so problems appear within minutes. Continuous delivery keeps every green change releasable, here a SHA-tagged image in ghcr.io; continuous deployment would also deploy it automatically.
  • On a pull request: checkout, JDK 25 with the Maven cache, ./mvnw -B verify with unit and MySQL Testcontainers tests, reports uploaded, the image built but not pushed. build-test is a required check, and merging needs it green, an approval and an up-to-date branch. After the merge, main runs the same tests and pushes sha-<commit>.

Order of execution

The pull request pipeline

Tap the steps in the order ShopLite runs them on a pull request.

Finish up

Mark complete & continue

Next: Project: ShopLite CI pipeline