I am trying to use an env variable in both the job and step level if condition. Whatever I do, it errors or it does not show my expected behavior. Here is my code
name: CI/CD
on:
push:
branches: [ other, stable ]
env:
BRANCH_NAME: ${{ github.head_ref || github.ref_name }}
STABLE_BRANCH_NAME: stable
jobs:
job1:
name: test
runs-on: [ self-hosted, linux, enterprise, .... ]
container:
image: some-image
steps:
- name: echo
run: echo $BRANCH_NAME
if I am on a branch named stable
it prints stable
Then I want to add if condition. I change the job to
jobs:
job1:
name: test
runs-on: [ self-hosted, linux, enterprise, .... ]
container:
image: some-image
if: env.BRANCH_NAME == env.STABLE_BRANCH_NAME
steps:
- name: echo
run: echo $BRANCH_NAME
it fails. wrong syntax
Then I change the job if condition to if: ${{ env.BRANCH_NAME == env.STABLE_BRANCH_NAME }} again does not work
I need two if conditions. one on the job and one on the step level like this
name: CI/CD
on:
push:
branches: [ other, stable ]
env:
BRANCH_NAME: ${{ github.head_ref || github.ref_name }}
STABLE_BRANCH_NAME: stable
jobs:
job1:
name: test
runs-on: [ self-hosted, linux, enterprise, .... ]
if: #### need help here: check the branch name is stable - This one des not work
container:
image: some-image
steps:
- name: echo
run: echo $BRANCH_NAME
if: ${{ env.STABLE_BRANCH_NAME != env.BRANCH_NAME }}. # This one works
On the step level I can do if: ${{ env.STABLE_BRANCH_NAME != env.BRANCH_NAME }} and it works but the same does not work on the job level
How should I do this?
Found these two
But isn't there an easier method?
According to context availability, the env context is not available with job level if.
The allowed contexts are:
jobs.<job_id>.if github, needs, vars, inputs
Alternatively, you can use the github and vars contexts here to achieve what you're trying to do.
Here's an example with the github context only:
if: ${{ github.ref_name == 'stable' }}
Or, with the vars context after configuring STABLE_BRANCH_NAME:
if: ${{ github.ref_name == vars.STABLE_BRANCH_NAME }}
You can use other operators to expand the condition according to your use case.
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