How to Set a Matrix From Previous Job Output in GitHub Actions
When the set of things to test is computed at runtime, the matrix has to come from a previous jobs output.
Emit a JSON array to ${GITHUB_OUTPUT} in a setup job, expose it as a job output, then feed it to the matrix with fromJSON.
Steps
- In a setup job, build the JSON array (e.g. from changed files).
- Write
matrix=<json>to${GITHUB_OUTPUT}and map it to a job output. - In the downstream job add
needs: setup. - Set
matrix: ${{ fromJSON(needs.setup.outputs.matrix) }}.
Workflow
.github/workflows/dynamic-matrix.yml
jobs:
setup:
runs-on: ubuntu-latest
outputs:
matrix: ${{ steps.gen.outputs.matrix }}
steps:
- id: gen
run: echo "matrix=[\"api\",\"web\",\"worker\"]" >> "${GITHUB_OUTPUT}"
test:
needs: setup
runs-on: ubuntu-latest
strategy:
matrix:
service: ${{ fromJSON(needs.setup.outputs.matrix) }}
steps:
- run: ./test.sh ${{ matrix.service }}Gotchas
- The output must be valid JSON; a stray trailing comma fails
fromJSONsilently as an empty matrix. - An empty array produces zero matrix jobs, which can look like a skipped step.
- Latchkey scales these dynamic matrix legs onto cheaper runners and retries any leg that fails transiently.
Related guides
How to Retry Only the Failed Matrix Legs in GitHub ActionsRe-run only the failed legs of a GitHub Actions matrix using fail-fast false and a per-step retry action, so…
How to Pass Data Between Jobs in GitHub ActionsPass values between GitHub Actions jobs using job outputs and the needs context, wiring a step output up to a…