Conditional GitHub Actions job

2 min read

471 words

With GitHub Actions it is possible to trigger jobs under certain conditions. GitHub provides the if for this purpose, which can be called at job level. In the following you will see how this can be achieved.

Syntax

As mentioned above the syntax of the if can be found on the sub level of the job name.

jobs:
	example-job:
		if: github.ref_name == 'main'

Here it is possible to check for different conditions. GitHub offers various variables in the [1], which can also be combined with the [2] provided.

The Ifs can follow two different formats. Both are equivalent to each other in the case.

  • if: github.ref_name == 'main'
  • if : {{if: github.ref_name == 'main'}}

Note: When using literals in expressions it is needed to enclose them using single quotes. Double quotes will fail [3]

Examples

jobs screenshot from GitHub

On push to main branch

The following GitHub Action will return "This is the main branch." only when the push is done to the named branch. Otherwise it will be skipped and the action will not start.

name: check-main-branch
on: 
  push:
  workflow_dispatch:

jobs:
  check-main-branch:
    if: github.ref_name == 'main'
    runs-on: ubuntu-latest
    steps:
      - run: echo "This is the main branch."

Output

check-main-branch output

On Release

This GitHub Action will only run when a release was published which has the tag name including -beta. When the tag is named different it is not triggered.

Requirement: Use of semantic versioning[4]. Example tag: 1.0.0-beta

name: check-beta-tag
on: 
  release: 
    types: [published]

jobs:
  beta-deployment:
    if: contains(github.ref_name, '-beta')
    runs-on: ubuntu-latest
    steps:
      - run: echo "This is the beta tag of $GITHUB_REF_NAME"

Note: $GITHUB_REF_NAME is part of the exposed environment variables [5] of the runner.

Output

Following is the output of the actions which are triggered after a release. In the first picture you can also see that the main-branch action is triggered but skipped, since the tag name is not main.

Actions overview after beta release Output after beta release

Additional Resources


  1. GitHub Actions Contexts ↩︎

  2. Expressions' built in functions ↩︎

  3. Expressions with literals ↩︎

  4. Semantic Versioning ↩︎

  5. Default Environment Variables ↩︎