Challenge 2: Make the Image Job Depend on Tests — Possible Solution ==================================================================== jobs: test: runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 - run: npm ci - run: npm test build-image: needs: test # <-- the added dependency runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 - run: docker build -t ghcr.io/myorg/myapp:${{ github.sha }} . - run: echo "${{ secrets.REGISTRY_TOKEN }}" | docker login ghcr.io -u ${{ github.actor }} --password-stdin - run: docker push ghcr.io/myorg/myapp:${{ github.sha }} WHY THIS WORKS -------------- - Adding needs: test to the build-image job is the exact mechanism Chapter 2 introduced for expressing job dependencies — it tells the CI system "do not start this job until the job named test has completed successfully." - Without needs: test, GitHub Actions would treat both jobs as INDEPENDENT by default and run them in PARALLEL — meaning build-image could start building and pushing an image at the exact same time test is still running, or even complete BEFORE test finishes and reports a failure. Adding needs: test eliminates this race entirely. - Critically, needs: doesn't just control ORDERING — per this chapter's own point ("a broken build never gets containerized or pushed at all"), if the test job FAILS, build-image is automatically SKIPPED entirely, not merely delayed until after test finishes. This is what actually enforces "only build/push an image for code that passed its tests" rather than just "build/push an image sometime after tests run, regardless of whether they passed." - This exactly mirrors this chapter's own worked example (the build-and-push job depending on test) — the only change needed here was renaming build-and-push to match this challenge's build-image job name and adding the same needs: test line that was already present in the chapter's reference workflow.