At the start of my workflow I want to conditionally set values for some ENV variables. These values should be global and apply to all jobs and steps. The following code is structurally invalid but it’s what I’m trying to accomplish
if: github.ref_name == "target branch" (for example)
env:
var1: 'Right Branch'
if: github.ref_name != "target branch"
env:
var1: 'Wrong Branch'
jobs:
...
There doesn't seem to be something native with Github Actions to achieve what you want.
As a workaround, you could use outputs to do it, using a setup job that would be used as a "needed" job for the subsequent jobs, where you would set the variables you want.
Here is an example using the output in the same job, or in a subsequent job:
jobs:
setup-job:
runs-on: ubuntu-latest
outputs:
var1: ${{ steps.set-variable.outputs.test }}
steps:
- uses: actions/checkout@v2
- name: Set test variable
id: set-variable
run: |
if [ ${{ github.ref }} != 'refs/heads/main' ]; then
echo "IS NOT main branch"
echo "::set-output name=test::abc"
else
echo "IS main branch"
echo "::set-output name=test::123"
fi
shell: bash
- name: Read exported variable
run: |
echo "OUTPUT: ${{ steps.check.test-env.test }}"
subsequent-job:
runs-on: ubuntu-latest
needs: [setup-job]
steps:
- uses: actions/checkout@v2
- name: Read exported variable
run: |
echo "OUTPUT: ${{needs.setup-job.outputs.var1}}"
Note: I couldn't do it using the $GITHUB_ENV variable (doing something like that echo "test=abc" >> $GITHUB_ENV) as it wasn't shared between jobs.
Here is the workflow file I used to test.
Here is the workflow run output.
Update 10/22: Warning: The set-output command is deprecated and will be disabled soon. Please upgrade to using Environment Files. For more information see: github.blog/changelog/…
Now, to set an environment variable, you'll need to use the following syntax:
echo "{environment_variable_name}={value}" >> $GITHUB_ENV
Thanks for showing us how to use $GITHUB_ENV. It was mentioned in the docs but an example speaks volumes. I need to conditionally set a dozen+ values and have opted for the following structures.
First, I moved all my setup code into a Composite Action, within my current repo. See How to share code between github actions in the same repository?
File: ./.github/workflows/env_setup/action.yml
runs:
using: "composite"
steps:
# Then I have the following block for each ENV variant
- shell: bash
if: <...>
run: |
echo "var1=val1
var2=val2
" >> $GITHUB_ENV
This gets accessed in my primary workflow as
my_job:
steps:
# Each Job needs to start with the following boilerplate
- uses: actions/checkout@v2
- uses: ./.github/workflows/env_setup
# REAL CODE STARTS HERE
- run: echo ${{ env.var1 }}
But I'm reconsidering replacing my env. code with your OUTPUTS structure. We'll see ... Cheers!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With