# Workflow details: expressions, matrices, caches and artifacts

Smarter, faster workflows: expressions and contexts, passing values between steps and jobs, a matrix of versions, dependency caching, and artifacts that carry the build between jobs.

Course: [CI/CD Pipelines](https://devops.rajeev.pro/courses/cicd), lesson 3. About 40 minutes, intermediate. Source: https://devops.rajeev.pro/courses/cicd/03-workflow-details

## What you will learn

- Read and write expressions with contexts such as github, matrix, steps and needs
- Pass values between steps with GITHUB_OUTPUT and between jobs with outputs
- Run conditional steps and jobs with if, success(), failure() and always()
- Test across versions and operating systems with a matrix, and control it with fail-fast and include
- Speed up installs with dependency caching, and know what makes a cache key correct
- Hand files between jobs with artifacts, and know their limits
- Stop wasted and overlapping runs with concurrency groups and path filters, and test against a real database with a service container

## Expressions and contexts

When workflows grow, hard-coded values and duplicated jobs become difficult to review. Expressions let a workflow
use facts about its current run, such as the branch, matrix entry or result of an earlier step. GitHub evaluates
an expression before the relevant step runs and reads the value from a context. In this lesson, you'll use those
values for conditions, matrices, caches, artifacts, concurrency and service containers.

| Context           | Holds                                          | Example                                                              |
| ----------------- | ---------------------------------------------- | -------------------------------------------------------------------- |
| `github`          | the event and repository                       | `github.ref_name`, `github.sha`, `github.actor`, `github.event_name` |
| `env`             | environment variables you set in the workflow  | `env.NODE_ENV`                                                       |
| `matrix`          | this job's matrix values                       | `matrix.node`                                                        |
| `steps`           | outputs and results of earlier steps (by `id`) | `steps.version.outputs.version`                                      |
| `needs`           | outputs and results of jobs this one needs     | `needs.build.outputs.version`, `needs.build.result`                  |
| `secrets`, `vars` | secrets and configuration variables            | `secrets.DEPLOY_KEY` (next lesson)                                   |
| `runner`          | the machine                                    | `runner.os`, `runner.temp`                                           |

Expressions also have functions: `contains()`, `startsWith()`, `format()`, `toJSON()`, `hashFiles()`, and
the status checks below.

### Passing values: steps and jobs

A step writes `name=value` to the file in `$GITHUB_OUTPUT`; later steps read it through the step's `id`.
A job publishes step outputs as **job outputs** for the jobs that need it:

```yaml
build:
  runs-on: ubuntu-latest
  outputs:
    version: ${{ steps.version.outputs.version }}     # 3. publish for other jobs
  steps:
    - id: version                                     # 1. give the step an id
      run: echo "version=1.0.${{ github.run_number }}-${GITHUB_SHA::7}" >> "$GITHUB_OUTPUT"
    - run: echo "Building ${{ steps.version.outputs.version }}"   # 2. read it in a later step

report:
  needs: build
  runs-on: ubuntu-latest
  steps:
    - run: echo "version ${{ needs.build.outputs.version }}"      # 4. read it in another job
```

```sh
$ echo "version=1.0.42-${GITHUB_SHA::7}" >> "$GITHUB_OUTPUT"   # what step 1 does, run locally
$ cat "$GITHUB_OUTPUT"
version=1.0.42-e3b0c44
```

| File                   | Effect                                                     |
| ---------------------- | ---------------------------------------------------------- |
| `$GITHUB_OUTPUT`       | a step output, read as `steps.<id>.outputs.<name>`         |
| `$GITHUB_ENV`          | an environment variable for **all later steps** in the job |
| `$GITHUB_PATH`         | a folder added to `PATH` for later steps                   |
| `$GITHUB_STEP_SUMMARY` | Markdown shown on the run's summary page                   |

`export VAR=x` doesn't survive the step: each `run:` is its own shell.

### Conditions: if

```yaml
- run: ./deploy.sh
  if: github.ref == 'refs/heads/main' && github.event_name == 'push'
- run: ./notify-team.sh "build failed"
  if: failure()                       # only when an earlier step failed
- run: ./upload-logs.sh
  if: always()                        # whatever happened
```

| Status function | True when                                 |
| --------------- | ----------------------------------------- |
| `success()`     | everything before succeeded (the default) |
| `failure()`     | something before failed                   |
| `always()`      | always, even when cancelled               |
| `cancelled()`   | the run was cancelled                     |

Inside `if:` the `${{ }}` is optional. Use `!cancelled()` rather than `always()` for cleanup that shouldn't
run when someone cancels a deploy on purpose.

## Matrix builds

A **matrix** runs the same job once per combination of values, in parallel. One block tests every Node
version you support:

> **Figure.** Animated. One job definition with a matrix fans out into four parallel jobs: Node 20, 22 and 24 on Ubuntu, plus Node 22 on Windows added with include. Each restores the npm cache, keyed on the hash of package-lock.json, so npm ci takes seconds. The build job waits until all four pass, packages shop-api-1.0.42.tgz and uploads it as the artifact shop-api. The report job runs on another machine and downloads the same file.
>
> Matrix: one job definition, many parallel jobs. Cache: faster installs. Artifact: this run's output, handed to the next job.

```yaml
test:
  name: test (node ${{ matrix.node }}, ${{ matrix.os }})
  runs-on: ${{ matrix.os }}
  strategy:
    fail-fast: false
    matrix:
      os: [ubuntu-latest]
      node: [20, 22, 24]
      include:
        - os: windows-latest     # one extra combination
          node: 22
  steps:
    - uses: actions/checkout@v7
    - uses: actions/setup-node@v7
      with:
        node-version: ${{ matrix.node }}
        cache: npm
    - run: npm ci
    - run: npm test
```

That's four jobs: Node 20, 22 and 24 on Ubuntu, plus Node 22 on Windows. `exclude:` removes combinations;
`max-parallel:` limits how many run at once.

`fail-fast` defaults to **true**: the first failure cancels the rest. For tests, set it to **false** so
every version reports, and you can see "only Node 20 fails" at a glance. Required status checks name each
matrix job, so a clear `name:` keeps the branch protection settings readable.

> **Video.** [Matrix Strategy in GitHub Actions | Single-Dimension and Multi-Dimension Matrix in GitHub Actions](https://www.youtube.com/watch?v=MFxqvXeft_U&t=300s) (DevOps Hint)

## Caching dependencies

Installing dependencies on every run is the slowest boring part of most pipelines. A **cache** saves a
folder after one run and restores it in the next. For the common package managers, the setup actions do
it for you:

```yaml
- uses: actions/setup-node@v7
  with:
    node-version: 22
    cache: npm            # caches npm's download folder, keyed on package-lock.json
- run: npm ci             # installs exactly the lockfile, using the cache
```

For anything else, use `actions/cache` with a key you build:

```yaml
- uses: actions/cache@v6
  with:
    path: ~/.cache/pip
    key: pip-${{ runner.os }}-${{ hashFiles('**/requirements.txt') }}
    restore-keys: |
      pip-${{ runner.os }}-
```

| Part           | Does                                                                              |
| -------------- | --------------------------------------------------------------------------------- |
| `key`          | exact match: the lockfile is unchanged, so the cache is exactly right             |
| `restore-keys` | fallback prefix: restore the newest similar cache, then install only what changed |
| `hashFiles()`  | a hash of the files: the key changes the moment dependencies change               |

Caches are per branch (a pull request can read caches from its base branch), unused ones are evicted after
about a week, and repositories have a size limit. So a pipeline must **still work with no cache**: it's
only ever a speed-up. Use `npm ci`, not `npm install`, in CI: it installs exactly what the lockfile says
and fails if the lockfile and `package.json` disagree.

> **Video.** [Cache GitHub Actions Workflow Dependencies](https://www.youtube.com/watch?v=lkn3FPRh5ps) (Cameron McKenzie)

## Artifacts: passing files between jobs

Jobs run on different machines, so the `dist/` one job builds isn't there for the next. Upload it as an
**artifact**:

```yaml
build:
  steps:
    - run: tar -czf "shop-api-${{ steps.version.outputs.version }}.tgz" -C dist .
    - uses: actions/upload-artifact@v7
      with:
        name: shop-api
        path: shop-api-*.tgz
        retention-days: 7

report:
  needs: build
  steps:
    - uses: actions/download-artifact@v8
      with:
        name: shop-api           # the files land in the working folder
```

Artifacts also appear on the run's page for anyone with access to download: test reports, coverage, build
logs. Each name can be uploaded **once per run**, so in a matrix give each job its own name, such as
`coverage-node-${{ matrix.node }}`. Retention defaults to 90 days and counts against storage; keep it short
for anything you rebuild anyway.

|                      | Cache                       | Artifact                                 |
| -------------------- | --------------------------- | ---------------------------------------- |
| For                  | speeding up **future** runs | keeping or passing **this run's** output |
| Typical content      | dependencies, build caches  | packages, test reports, coverage         |
| Guaranteed to exist? | no: may be evicted          | yes, until it expires                    |

> **Build once, deploy that.** The artifact the build job uploads is the one you test, stage and deploy (lesson 1's "build once, deploy many"). Never rebuild for production: a second build can pull different dependencies and ship code that was never tested.

> **Video.** [GitHub Actions - Upload Artifacts](https://www.youtube.com/watch?v=vlySg5UPIm4) (Mickey Gousset)

## Concurrency: one run per branch

Push three commits to a pull request in a minute and you get three runs, though only the last one matters.
Merge two pull requests close together and two deploys race each other to the same server. A **concurrency
group** fixes both: GitHub allows one running and one pending run per group, and a newer pending run
replaces the older one.

```yaml
concurrency:
  group: ${{ github.workflow }}-${{ github.ref }}                 # one lane per workflow and branch
  cancel-in-progress: ${{ github.event_name == 'pull_request' }}  # PRs: kill the outdated run
```

| Workflow       | `cancel-in-progress` | Why                                                              |
| -------------- | -------------------- | ---------------------------------------------------------------- |
| PR checks      | `true`               | an older commit's result is useless once a newer one is pushed   |
| Deploy         | `false`              | stopping a deploy halfway can leave a server with half a release |
| Main branch CI | `false`              | every commit on main should get a result, for `git bisect` later |

A deploy workflow uses a fixed group name, such as `deploy-production`, so deploys from any branch or
workflow wait in one queue. `concurrency:` also works on a single job, when only the deploy job needs
the lock.

> **Video.** [GitHub Actions Tutorial: Advanced Concepts You Should Know (Part 2)](https://www.youtube.com/watch?v=TKj0KyX8m8o&t=469s) (KodeKloud)

## Path filters: run only when it matters

Fixing a typo in the README shouldn't run twenty minutes of tests. `paths` runs a workflow only when a
matching file changed; `paths-ignore` skips it when **only** ignored files changed:

```yaml
on:
  pull_request:
    paths-ignore:
      - 'docs/**'
      - '**/*.md'
```

You can't use both on the same event. A deploy workflow that tries:

```yaml
name: deploy
on:
  push:
    branches: [main]
    paths: ['src/**', 'package*.json']
    paths-ignore: ['docs/**']
```

actionlint catches it:

```sh
$ actionlint
.github/workflows/deploy.yml:6:5: both "paths" and "paths-ignore" filters cannot be used for the same event "push". note: use '!' to negate patterns [events]
  |
6 |     paths-ignore: ['docs/**']
  |     ^~~~~~~~~~~~~
```

The fix is one list with a `!` exception: `paths: ['src/**', 'package*.json', '!src/**/*.md']`.

One trap: when a path filter skips a workflow, its checks never report, and a pull request that **requires**
them waits forever as _Expected_. Either don't make path-filtered workflows required, or keep the workflow
always running and decide inside a job what to skip (lesson 12 does this for monorepos).

> **Video.** [Mastering GitHub Actions: Advanced Event Filtering (Branches, Paths & Types Explained)](https://www.youtube.com/watch?v=T56OFJLid8Y) (The DevOps Toolkit)

## Service containers: a real database for tests

Integration tests want a real database, not mocks. `services:` starts containers next to the job, waits for
their health check, and throws them away when the job ends, so every run starts empty:

```yaml
integration:
  runs-on: ubuntu-latest
  services:
    postgres:
      image: postgres:16-alpine
      env:
        POSTGRES_USER: shop
        POSTGRES_PASSWORD: test-only        # a throwaway test password, not a secret
        POSTGRES_DB: shop_test
      ports:
        - 5432:5432
      options: >-
        --health-cmd "pg_isready -U shop -d shop_test"
        --health-interval 5s
        --health-timeout 5s
        --health-retries 10
  env:
    DATABASE_URL: postgres://shop:test-only@localhost:5432/shop_test
  steps:
    - uses: actions/checkout@v7
    - uses: actions/setup-node@v7
      with:
        node-version: 22
        cache: npm
    - run: npm ci
    - run: npm run test:integration
```

That is the same as running the container yourself, which is how to debug it locally:

```sh
$ docker run -d --name ci-postgres -e POSTGRES_USER=shop -e POSTGRES_PASSWORD=test-only -e POSTGRES_DB=shop_test \
    -p 5432:5432 --health-cmd "pg_isready -U shop -d shop_test" --health-interval 5s \
    --health-timeout 5s --health-retries 10 postgres:16-alpine
$ docker ps --filter name=ci-postgres --format '{{.Names}}\t{{.Status}}'
ci-postgres	Up 15 seconds (healthy)
$ docker run --rm --network host postgres:16-alpine psql "postgres://shop:test-only@localhost:5432/shop_test" \
    -c "select current_database(), current_user;"
 current_database | current_user
------------------+--------------
 shop_test        | shop
(1 row)
$ docker rm -f ci-postgres
```

When the job runs directly on the runner (as above), it reaches the service on `localhost` through the
mapped port. When the job itself runs in a container (`container: node:22`), it reaches the service by its
name instead, `postgres:5432`, with no `ports:` needed. Service containers need a Linux runner.

## Mission: Test on every Node version, build once, hand it on

Extend shop-api's CI: run the tests as a matrix on Node 20, 22 and 24 plus Windows, with npm caching and fail-fast off; then a build job that creates a versioned package, uploads it as an artifact and writes a run summary; and a report job that always runs and downloads it.

- You need: The shop-api repository from the previous lesson
- You'll have: A run with 4 test jobs, a build artifact and a summary

```sh
$ npm install                      # creates package-lock.json, which npm ci and the cache need
$ git add package-lock.json
$ nano .github/workflows/ci.yml    # the test matrix, build and report jobs from this lesson
$ actionlint && echo "workflow OK"
workflow OK
$ git commit -am "ci: test on a matrix, upload the build" && git push
$ gh run watch                     # follow the run
$ gh run download --name shop-api  # the artifact, on your machine
$ tar -tzf shop-api-*.tgz
./
./package.json
./src/
./src/server.js
./src/app.js
```

The run page shows four test jobs side by side, then **build**, then **report**. The second run's install
step is faster: `setup-node` prints `Cache restored from key: node-cache-…`. The summary page shows
`Built shop-api 1.0.N-<sha>`.

## Try it

- See the whole event payload once: a step with `EVENT: ${{ toJSON(github.event) }}` under `env:` that runs `echo "$EVENT"`. Then delete it.
- Turn the test job into a matrix over Node 20, 22 and 24, and read the job names it creates.
- Set `fail-fast: false`, break a test only on Node 20, and see the other versions still finish.
- Add `cache: npm` to setup-node and compare the install time of the first and second run.
- Upload `dist/` as an artifact in one job and list it in another job with download-artifact.
- Write a value to `$GITHUB_STEP_SUMMARY` and find it on the run's summary page.
- Add `concurrency` with `cancel-in-progress` for pull requests, push three commits quickly, and watch the first two runs get cancelled.

## Quiz

1. How does one step pass a value to a later step in the same job?
   - export VAR=value
   - **echo "name=value" >> "$GITHUB_OUTPUT" in a step with an id, then read steps.<id>.outputs.name** (answer)
   - Write it to /tmp
   - Steps can't share values
   Why: export only lives inside that step's shell. GITHUB_OUTPUT sets step outputs; GITHUB_ENV sets environment variables for all later steps.

2. A notify job must run even when the build fails. Which condition?
   - if: success()
   - **if: always()** (answer)
   - if: failure() == false
   - No condition
   Why: Jobs and steps run only if everything before succeeded, unless you say otherwise. always() runs regardless; failure() runs only after a failure.

3. A matrix of 3 Node versions has fail-fast true (the default). Node 20 fails. What happens?
   - The others keep running
   - **GitHub cancels the other in-progress matrix jobs** (answer)
   - The whole workflow retries
   - Nothing
   Why: Quick feedback, but you lose the other results. fail-fast false lets every version finish, so you see whether only one version breaks.

4. Why does a good cache key include hashFiles('**/package-lock.json')?
   - To make the key longer
   - **So the cache changes exactly when the dependencies change, and a stale cache is never reused** (answer)
   - GitHub requires it
   - It encrypts the cache
   Why: Same lockfile, same key, cache hit. A changed lockfile gives a new key; restore-keys can still fall back to an older cache as a starting point.

5. What is the difference between a cache and an artifact?
   - None
   - **A cache speeds up future runs (dependencies); an artifact is a run's output (builds, reports) you keep or pass to another job** (answer)
   - Artifacts are faster
   - Caches are permanent
   Why: Never rely on a cache existing: it can be evicted. Artifacts are the reliable way to move build output between jobs.

6. A workflow has `concurrency: { group: ci-${{ github.ref }}, cancel-in-progress: true }`. You push three commits to a pull request within a minute. What happens?
   - Three runs finish, one after another
   - All three run at the same time
   - **Each new run cancels the one still running, so only the last commit is fully tested** (answer)
   - The third push is rejected
   Why: Same branch, same group. Only the newest commit matters on a pull request, so cancelling the older runs saves minutes. Never do this for a deploy: a half-finished deploy is worse than a queued one.

7. Your integration tests need a real PostgreSQL in GitHub Actions. What is the cleanest way?
   - **A service container with a health check, so the job starts only once the database answers** (answer)
   - Point the tests at the production database
   - Mock every query
   - apt-get install postgresql in a step and hope it has started
   Why: services: starts the container next to the job and waits for its health check. It is thrown away after the job, so every run starts from an empty database.

## Resources

- [GitHub Docs: expressions](https://docs.github.com/en/actions/reference/workflows-and-actions/expressions) (GitHub Docs)
- [GitHub Docs: contexts reference](https://docs.github.com/en/actions/reference/workflows-and-actions/contexts) (GitHub Docs)
- [GitHub Docs: running variations of jobs (matrix)](https://docs.github.com/en/actions/how-tos/write-workflows/choose-what-workflows-do/run-job-variations) (GitHub Docs)
- [GitHub Docs: dependency caching reference](https://docs.github.com/en/actions/reference/workflows-and-actions/dependency-caching) (GitHub Docs)
- [actions/upload-artifact](https://github.com/actions/upload-artifact) (GitHub)
