How do I specify or change an environment variable as part of a job matrix?
For example, here I want my job to echo "Two" and "Three" instead of "One", but github completely ignores the definition or change of the environment variable in the matrix:
name: test-test-test
on:
push:
branches: [ main, develop ]
pull_request:
branches: [ main, develop ]
env:
MY_VAR: One
jobs:
test:
runs-on: ubuntu-latest
strategy:
matrix:
include:
- env:
MY_VAR: Two
- env:
MY_VAR: Three
steps:
- run: echo "$MY_VAR2"
yields echo "One"
and echo "One"
in both jobs.
2
Answers
Use this context to access information about environment variables that have been set in a workflow, step, or job. Note that you cannot use the env context in the value of the id and uses keys within a step. An example is
env.env_var
.GitHub provides extensive documentation about contexts at
https://docs.github.com/en/actions/learn-github-actions/contexts.
The syntax you used won’t work for matrix. As stated in the official documentation:
In your case, to access the matrix
env
variable you set in theinclude
field list, you would need to use${{ matrix.env.MY_VAR }}
.Something like this:
This will generate 2
test
jobs:test (Two)
andtest (Three)
.I made a test here if you want to have a look.
Conclusion:
Basically, the
env
you set at the workflow level isn’t the sameenv
set in the matrix strategy, so you can’t substitute the value there.Alternative
What you could do eventually (as
@Adam
stated in the other answer) is to set theenv
value at the workflow level for it to work, in theenvironment
context. (Reference in the documentation + another workflow example).Example:
But depending on what you plan to achieve, a matrix strategy you be more efficient.