Sub topic 8
Running jobs and steps conditionally with if
This chapter assumes you can read a workflow file (on, jobs, steps) and know what a context such as github is. The if keyword lets a job or step run only when an expression is true. Otherwise GitHub skips it.
Where if can go
You can put if on a job or on a step.
- A job-level
ifis evaluated before a runner is assigned. A skipped job uses no runner. - A step-level
ifis evaluated just before that step runs, so it can see the results of earlier steps.
name: conditional
on:
push:
pull_request:
jobs:
test:
runs-on: ubuntu-latest
steps:
- name: Always runs
run: echo "Testing"
- name: Only on main
if: github.ref == 'refs/heads/main'
run: echo "On main"
- name: Not a draft pull request
if: ${{ github.event_name == 'pull_request' && !github.event.pull_request.draft }}
run: echo "Ready for review"
deploy:
needs: test
if: github.event_name == 'push' && github.ref == 'refs/heads/main'
runs-on: ubuntu-latest
steps:
- run: echo "Deploying"How the condition is evaluated
GitHub treats the whole if value as an expression, so ${{ }} is optional. The value is converted to a Boolean. false, 0, '' and null are falsy. Most other values are truthy.
Gotchas
- A leading
!needs${{ }}. In YAML,!starts a tag, soif: !cancelled()is a syntax error. Writeif: ${{ !cancelled() }}. - Do not mix text with
${{ }}.if: ${{ github.ref }} == 'refs/heads/main'becomes a non-empty string, which is always truthy. Keep the whole comparison inside one expression. - Secrets are not available in step
if. Map the secret intoenvand testenv.API_TOKEN != '', as shown in the secrets chapter. - Job-level
ifsees fewer contexts. It can readgithub,needs,varsandinputs. It cannot readenvorsteps, because no steps have run yet.
Implicit success
Without a status function, GitHub adds success() && to your condition. A step is skipped after an earlier failure, and a job is skipped when a job it needs failed or was skipped. If your condition includes a status function such as failure() or always(), that implicit check is not added. The next chapter covers these functions.
Exercise
A step has if: !startsWith(github.ref, 'refs/tags/') and the workflow fails to parse. What is wrong, and how do you fix it?
Show answer
A value starting with ! is read by YAML as a tag, not as an expression. Wrap the expression in ${{ }}: if: ${{ !startsWith(github.ref, 'refs/tags/') }}.
Exercise
You write if: ${{ github.ref }} == 'refs/heads/main' and the step runs on every branch. Why?
Show answer
The ${{ }} part is replaced by the ref string, and the leftover text makes the whole condition a non-empty string, which is truthy. Put the full comparison inside the expression: if: github.ref == 'refs/heads/main'.