Sub topic 15
Generating a matrix at runtime with fromJSON
This chapter assumes you can read a workflow file with several jobs, and that you know strategy.matrix, include and exclude, and cache keys from earlier chapters. You should also be comfortable with needs and basic shell scripting. The shell examples use jq, which is preinstalled on GitHub-hosted Ubuntu runners.
Why build a matrix at runtime
A static matrix is written into the workflow file. That works when the list of combinations rarely changes. It breaks down when the list depends on the repository's contents at the moment of the run. Common cases:
- A monorepo where each directory under
packages/should be tested separately, and new packages appear without anyone editing the workflow. - A matrix that should only contain the packages touched by the current pull request.
- A list of versions kept in a file such as
.node-versions, shared with other tools.
The workflow cannot run a script while it is being parsed, so the matrix must be produced by an earlier job. That job writes the matrix as JSON into a job output. A later job reads the output with needs and turns it back into a structure with fromJSON.
The mechanism
Three pieces connect the two jobs:
- A step in the first job writes
name=valueto the file whose path is in$GITHUB_OUTPUT. - The first job exposes that step output under
jobs.<id>.outputs. - The second job declares
needs: <first job>and setsstrategy.matrixto${{ fromJSON(needs.<first job>.outputs.<name>) }}.
Job outputs are always strings. fromJSON parses that string into an object or array, and the matrix machinery then treats it like a matrix you had typed by hand.
A minimal example
This is the smallest working version. Note the quoting: the JSON sits inside single quotes in a run: | block, so the double quotes need no escaping.
jobs:
plan:
runs-on: ubuntu-latest
outputs:
matrix: ${{ steps.set.outputs.matrix }}
steps:
- id: set
run: |
echo 'matrix={"node":[18,20,22]}' >> "$GITHUB_OUTPUT"
test:
needs: plan
runs-on: ubuntu-latest
strategy:
matrix: ${{ fromJSON(needs.plan.outputs.matrix) }}
steps:
- uses: actions/setup-node@v4
with:
node-version: ${{ matrix.node }}
- run: node --versionThe whole matrix value comes from JSON here. The output must be an object whose keys are matrix variables, exactly as if you had written them under matrix:. Here that gives three jobs. You can also mix: write os: [ubuntu-latest] statically and set only one key from JSON by using ${{ fromJSON(...) }} on that key alone.
Computing the list from the repository
A fixed string teaches the wiring but gains nothing over a static matrix. The useful version discovers the list. This example finds every directory under packages/ and tests each one.
jobs:
plan:
runs-on: ubuntu-latest
outputs:
packages: ${{ steps.find.outputs.packages }}
count: ${{ steps.find.outputs.count }}
steps:
- uses: actions/checkout@v4
- id: find
run: |
packages=$(find packages -mindepth 1 -maxdepth 1 -type d -printf '%f\n' | sort | jq -R . | jq -sc .)
echo "packages=$packages" >> "$GITHUB_OUTPUT"
echo "count=$(jq length <<< "$packages")" >> "$GITHUB_OUTPUT"
test:
needs: plan
if: needs.plan.outputs.count != '0'
runs-on: ubuntu-latest
strategy:
matrix:
package: ${{ fromJSON(needs.plan.outputs.packages) }}
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version: 20
cache: npm
cache-dependency-path: packages/${{ matrix.package }}/package-lock.json
- run: npm ci
working-directory: packages/${{ matrix.package }}
- run: npm test
working-directory: packages/${{ matrix.package }}Points worth noticing:
jq -R .turns each line into a JSON string, andjq -sc .collects them into a compact array such as["api","web"].- The
-cflag matters. It keeps the JSON on one line, whichname=valueoutput requires. - The planning job also publishes
count. Theifon the test job skips it when no packages exist, so the run does not fail on an empty matrix. - The built-in cache of
setup-nodeusescache-dependency-pathto hash each package's own lock file. Each package therefore gets its own cache entry without extra work.
Producing include objects
When each job needs several related values, emit an include list. Every object in the list becomes one job, and its keys become matrix variables.
jobs:
plan:
runs-on: ubuntu-latest
outputs:
matrix: ${{ steps.set.outputs.matrix }}
steps:
- id: set
run: |
matrix=$(jq -nc '{include: [
{name: "api", dir: "services/api", node: 20},
{name: "web", dir: "services/web", node: 22}
]}')
echo "matrix=$matrix" >> "$GITHUB_OUTPUT"
build:
needs: plan
runs-on: ubuntu-latest
strategy:
matrix: ${{ fromJSON(needs.plan.outputs.matrix) }}
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version: ${{ matrix.node }}
- run: echo "Building ${{ matrix.name }} in ${{ matrix.dir }}"This form avoids a cross product. The two jobs run exactly the combinations listed, with no accidental api on Node 22. It is usually the best shape when the planning script already knows which combinations are valid.
Keeping cache keys distinct
A generated matrix has the same cache rule as a static one: the key must include every variable that changes the cached content. If you use actions/cache directly, add the matrix values to the key.
- uses: actions/cache@v4
with:
path: ~/.npm
key: ${{ runner.os }}-${{ matrix.name }}-node${{ matrix.node }}-${{ hashFiles(format('{0}/package-lock.json', matrix.dir)) }}
restore-keys: |
${{ runner.os }}-${{ matrix.name }}-node${{ matrix.node }}-hashFiles takes a glob pattern, and you can build one from a matrix value with format. Because the value comes from generated data, check that it contains no characters that would change the glob's meaning.
Limits and failure modes
| Problem | Cause | Fix |
|---|---|---|
| `Unexpected value` or a JSON parse error at the matrix | The output is empty, invalid JSON, or spans several lines | Print the output in the planning job, and use `jq -c` |
| The matrix job fails with an empty matrix error | The array or `include` list has no entries | Output a count and guard the job with `if` |
| Output is missing | The step has no `id`, or the job's `outputs` block does not reference it | Check both names match exactly |
| Workflow rejected or truncated | More than 256 jobs from one matrix | Split the work or group items into batches |
| Output silently absent | The value contained a secret, which GitHub refuses to pass between jobs | Never put secrets in matrix data |
| Type surprises | Outputs are strings, so `"20"` and `20` differ after parsing | Emit numbers unquoted in JSON |
Other limits to remember:
- A single job output can hold at most 1 MB, and all outputs in a run together at most 50 MB. A list of names fits easily. A list of file contents would not.
- A matrix can produce at most 256 jobs per workflow run. A repository with hundreds of packages needs batching, for example grouping packages into chunks and looping inside each job.
- Multi-line values need the heredoc form with a delimiter in
$GITHUB_OUTPUT. Avoid that for matrices and keep the JSON compact on one line. - If the planning job fails or is skipped, every job that needs it is skipped too. That is correct behavior, but it can look like the tests vanished.
Choosing between static and dynamic
Use a static matrix when the combinations are few and stable. It is easier to read, and the job list appears in the workflow file. Use a dynamic matrix when the list is derived from files or from the change under test. The cost is an extra job that runs first, typically a few seconds plus runner startup, and one more place where errors can occur.
Exercise
A planning job writes matrix={"include":[]} to GITHUB_OUTPUT, and the test job uses strategy.matrix: ${{ fromJSON(needs.plan.outputs.matrix) }}. The test job fails at startup. What two changes make the workflow succeed cleanly when there is nothing to test?
Show answer
The empty include list produces a matrix with no jobs, which GitHub treats as an error. First, have the planning step also write a count or boolean output, for example count=$(jq '.include | length' <<< "$matrix"), and expose it under outputs. Second, add if: needs.plan.outputs.count != '0' to the test job so it is skipped instead of failing.
Exercise
You generate a matrix of package names and use actions/cache with key: ${{ runner.os }}-npm-${{ hashFiles('**/package-lock.json') }}. What goes wrong, and how do you fix it?
Show answer
Every matrix job computes the same key from all lock files, so the first job to finish saves the cache and the others reuse content built for a different package, or find the key already taken and save nothing. Include the matrix value in the key and hash only that package's lock file, for example ${{ runner.os }}-${{ matrix.package }}-npm-${{ hashFiles(format('packages/{0}/package-lock.json', matrix.package)) }}.