Sub topic 15
The matrix and strategy contexts
This chapter assumes you know basic workflow syntax and how ${{ }} expressions work. It also assumes you have seen a strategy.matrix block before.
Two contexts, two jobs
A matrix runs one job definition many times with different values. Two contexts expose those values:
- The
matrixcontext holds the values for the current job copy. You read a property withmatrix.<name>. - The
strategycontext holds settings of the matrix run:strategy.fail-fast,strategy.max-parallel,strategy.job-index(counting from 0), andstrategy.job-total.
GitHub expands the matrix before any runner starts. Each combination becomes its own job, and each job sees only its own matrix values.
A worked example
name: matrix-demo
on: push
jobs:
test:
runs-on: ${{ matrix.os }}
strategy:
fail-fast: false
max-parallel: 2
matrix:
os: [ubuntu-latest, windows-latest]
node: ["18", "20"]
include:
- os: ubuntu-latest
node: "22"
experimental: true
exclude:
- os: windows-latest
node: "18"
steps:
- name: Show matrix and strategy values
shell: bash
env:
OS_NAME: ${{ matrix.os }}
NODE_VERSION: ${{ matrix.node }}
EXPERIMENTAL: ${{ matrix.experimental }}
INDEX: ${{ strategy.job-index }}
TOTAL: ${{ strategy.job-total }}
run: echo "Job $INDEX of $TOTAL on $OS_NAME with Node $NODE_VERSION (experimental='$EXPERIMENTAL')"The two axes give four combinations. exclude removes windows-latest with Node 18, leaving three. include adds one more job, because its node: "22" does not match any existing combination. The result is four jobs, so strategy.job-total is 4.
How the pieces behave
runs-oncan use the matrix. Thematrixcontext is available in job-level keys such asruns-on,name,env, andif, and in steps. It is not available inneeds.excludeis applied first.includeis applied afterward, so anincludeentry can add back a combination you excluded.includecan add properties. If an entry matches an existing combination on the original axes, its extra keys, such asexperimental, are added to that job. If it matches nothing, it creates a new job.- Missing properties are empty. In the example,
matrix.experimentalis an empty string in the three jobs that do not set it. fail-fastdefaults to true. One failure cancels the other running matrix jobs. Setfail-fast: falseto let all of them finish.
You can also pass matrix values to if, for example if: matrix.experimental == true. For a matrix built at run time, see the fromJSON chapter.
Exercise
A matrix has os: [ubuntu-latest, windows-latest, macos-latest] and node: ["18", "20"]. It also has exclude: [{os: macos-latest, node: "18"}] and no include. How many jobs run, and what is strategy.job-total?
Show answer
Six combinations minus one excluded gives 5 jobs. Each job sees strategy.job-total as 5, and strategy.job-index runs from 0 to 4.