How to Dynamically Generate a Matrix in GitHub Actions
A setup job emits a JSON array that a downstream matrix consumes via fromJSON.
Compute the matrix as JSON in a setup job, expose it as an output, then set matrix: ${{ fromJSON(needs.setup.outputs.matrix) }} in the build job.
Steps
- In a setup job, build a JSON array and write it to
$GITHUB_OUTPUT. - Expose it as a job output.
- Reference
fromJSON(needs.setup.outputs.matrix)in the next job.
Workflow
.github/workflows/ci.yml
jobs:
setup:
runs-on: ubuntu-latest
outputs:
matrix: ${{ steps.gen.outputs.matrix }}
steps:
- id: gen
run: echo "matrix=$(ls packages | jq -R . | jq -cs .)" >> "$GITHUB_OUTPUT"
build:
needs: setup
strategy:
matrix:
pkg: ${{ fromJSON(needs.setup.outputs.matrix) }}
runs-on: ubuntu-latest
steps:
- run: cd packages/${{ matrix.pkg }} && npm testGotchas
- The generated JSON must be compact and valid, or
fromJSONfails the run. - An empty array produces zero jobs; guard against it.
Related guides
How to Use a Matrix Build in GitHub ActionsUse a build matrix in GitHub Actions to run one job across many versions in parallel with strategy.matrix, fa…
How to Use Outputs From a Matrix in GitHub ActionsCollect results from matrix jobs in GitHub Actions by writing per-leg artifacts, since matrix job outputs col…