If I want to let a user override the default values in the matrix, how do I do that?
Consider the following simplified example:
name: CICD
on:
push:
branches:
- main
workflow_dispatch:
inputs:
py_version:
description: "Python version"
default: "3.11"
jobs:
test:
runs-on: ubuntu-22.04
strategy:
matrix:
py_version: [3.7, 3.10]
steps:
- uses: actions/setup-python@v4
with:
python-version: ${{ matrix.py_version }}
I want to let a user override the py_version
matrix list with the list provided in the workflow_dispatch
input. Is there a way?
I tried asking ChatGPT but it messed things up all the time. I went looking for a way to dynamically build the matrix JSON, but this looks complicated and I failed to find a working solution.
PS: Is it possible to let the user provide a list-like value in the inputs, say, [3.5, 2.7]
that would be populated in the matrix? I am fine with a single value as well, though.
You can use a comma-separated list along with format()
and fromJSON()
functions; and, OR operator ||
like this:
name: populate_matrix_from_inputs
on:
push:
branches: [main]
workflow_dispatch:
inputs:
python_version:
description: 'Comma-separated list of Python versions e.g. "3.10","3.11"'
default: '"3.11"'
required: true
jobs:
ci:
runs-on: ubuntu-latest
strategy:
matrix:
python_version: ${{ fromJSON(format('[{0}]', inputs.python_version || '"3.7","3.10"')) }}
steps:
- uses: actions/setup-python@v4
with:
python-version: ${{ matrix.python_version }}
Inputs
Runs
NOTE: Quotes around versions are mandatory to avoid the removal of trailing zeros during conversions. For example, without quotes, 3.10
would become 3.1
which is not a valid version. If such cases are not an issue, quotes may be avoided.