Skip to content
Latchkey

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 fromJSON silently 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

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