Sub topic 16
Building a matrix at run time with fromJSON
This chapter assumes you know static strategy.matrix, job outputs with needs, and the ${{ }} expression syntax from earlier chapters.
Building a matrix at run time with fromJSON
A static matrix is fixed in the YAML file. Sometimes the list depends on the repository, such as the packages that changed or the versions a script reports. In that case, one job computes the list and the matrix reads it.
Job outputs are always strings. The matrix needs a list, so you convert the string with fromJSON.
name: dynamic-matrix
on: push
jobs:
plan:
runs-on: ubuntu-latest
outputs:
versions: ${{ steps.set.outputs.versions }}
steps:
- id: set
run: echo 'versions=["18","20","22"]' >> "$GITHUB_OUTPUT"
test:
needs: plan
runs-on: ubuntu-latest
strategy:
matrix:
node: ${{ fromJSON(needs.plan.outputs.versions) }}
steps:
- run: echo "Testing on Node ${{ matrix.node }}"The plan job writes a JSON array to GITHUB_OUTPUT. The job output versions exposes it. The test job reads it through needs and creates one run per element.
Workflow inputs for manual and reusable workflows
Inputs let a caller pass values into a workflow. Two triggers accept them:
workflow_dispatchtakes inputs when a person starts a run manually.workflow_calltakes inputs when another workflow calls this one as a reusable workflow.
You read both through the inputs context.
name: release
on:
workflow_dispatch:
inputs:
environment:
description: Target environment
type: choice
options: [staging, production]
default: staging
dry-run:
description: Skip the real deploy
type: boolean
default: true
workflow_call:
inputs:
environment:
type: string
required: true
dry-run:
type: boolean
default: false
jobs:
deploy:
runs-on: ubuntu-latest
steps:
- name: Real deploy
if: ${{ !inputs.dry-run }}
env:
TARGET: ${{ inputs.environment }}
run: echo "Deploying to $TARGET"The inputs context keeps the declared type, so inputs.dry-run is a real boolean and !inputs.dry-run works. The older github.event.inputs context turns everything into strings, so prefer inputs.
The input is mapped into env before the shell uses it, following the injection rule from the previous chapter. A free-text input is untrusted data.
Exercise
A job output contains the string ["a","b"]. Why does matrix: ${{ needs.plan.outputs.list }} fail, and what fixes it?
Show answer
Job outputs are strings, and the matrix needs a list. Wrapping the value in fromJSON(...) converts the string into an array, so the matrix creates one run for each element.
Exercise
Why is inputs.dry-run better than github.event.inputs.dry-run for a boolean input?
Show answer
The inputs context keeps the boolean type, so !inputs.dry-run works as expected. github.event.inputs stores every value as a string.