Skip to content
Latchkey

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 test

Gotchas

  • The generated JSON must be compact and valid, or fromJSON fails the run.
  • An empty array produces zero jobs; guard against it.

Related guides

Run this faster and cheaper on Latchkey managed runners. Start free →