How to Run a Matrix Only on Certain Events in GitHub Actions
Compute the matrix in a setup job keyed on github.event_name so pull requests run a subset and main runs the full fan-out.
A setup job branches on github.event_name, emits a small or large JSON list, and the build job consumes it with fromJSON.
Steps
- In a setup job, choose the version list based on the event.
- Emit it as JSON to
$GITHUB_OUTPUT. - Consume it with
fromJSONin the build matrix.
Workflow
.github/workflows/ci.yml
jobs:
setup:
runs-on: ubuntu-latest
outputs:
versions: ${{ steps.pick.outputs.versions }}
steps:
- id: pick
run: |
if [ "${{ github.event_name }}" = "pull_request" ]; then
echo 'versions=[20]' >> "$GITHUB_OUTPUT"
else
echo 'versions=[18,20,22]' >> "$GITHUB_OUTPUT"
fi
test:
needs: setup
runs-on: ubuntu-latest
strategy:
matrix:
node: ${{ fromJSON(needs.setup.outputs.versions) }}
steps:
- run: echo "Testing on ${{ matrix.node }}"Gotchas
- Keep required-check names stable across events so branch protection still matches.
- The emitted string must be valid JSON, including the brackets.
Related guides
How to Build a Dynamic Matrix From JSON in GitHub ActionsGenerate a GitHub Actions matrix at runtime by having a setup job emit JSON and a downstream job read it with…
How to Build a Matrix From Changed Files in GitHub ActionsFan out a GitHub Actions matrix only over the packages that changed by detecting changed files in a setup job…