Perform a conditional step in GitHub Actions job

2 min read

300 words

The previous post was about conditional jobs [1]. GitHub also offers the possibility of providing individual steps with a condition. The usage is almost identical to the conditional jobs. How you can implement them is described below.

As with conditional jobs, it is possible to work with and without expression symbols ${{}}. As with the jobs, literals should be used with a single quote '. [2]

steps:
  - run: echo 'I run when the conidition is met'
    if: ${{ <expression> }}
	- run: echo 'I run when the conidition is met'
    if: <expression>

Full action example

In the following action, a default value is set as an environment variable. If the condition is met, in this case a release tag containing -beta, the environment variable is changed to the value MY_BETA_VALUE. In this way, a different build can be initiated or the deployment can be changed in the subsequent steps. In addition, predefined actions can be provided with a condition. The possibilities are up to the user.

name: override-env
on: 
	release: 
		types: [published]
jobs:
  example-job:
    runs-on: ubuntu-latest
    env:
	    MY_ENV: MY_VALUE
    steps:
      - uses: actions/checkout@v3
      - run: echo "$MY_ENV"
		  - if: contains(github.ref_name, '-beta') # or $GITHUB_REF
		    run: echo "MY_ENV='MY_BETA_VALUE'" >> $GITHUB_ENV
      - run: echo "$MY_ENV"

Additional Resources


  1. Conditional GitHub Actions job ↩︎

  2. Expressions with literals ↩︎