Sub topic 11
Running steps and jobs conditionally
This chapter assumes you can read a workflow file, know what jobs and steps are, and have seen ${{ }} expressions and contexts. Here you will use the if key to decide whether a step or a job runs.
The `if` key
Both jobs and steps accept an if key. If its expression evaluates to true, the step or job runs. If not, it is skipped, and the run log marks it as skipped.
Inside if, the ${{ }} wrapper is optional. These two lines are equivalent:
if: github.ref == 'refs/heads/main'
if: ${{ github.ref == 'refs/heads/main' }}A job-level condition
A job with if is skipped when the condition is false. Here, the deploy job runs only for pushes to main.
name: Release
on:
push:
pull_request:
jobs:
test:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- run: echo "Testing"
deploy:
needs: test
if: github.event_name == 'push' && github.ref == 'refs/heads/main'
runs-on: ubuntu-latest
steps:
- run: echo "Deploying"Status check functions
By default, a step runs only if all earlier steps succeeded. Status functions change that.
| Function | True when |
|---|---|
| `success()` | All previous steps or needed jobs succeeded. This is the default. |
| `failure()` | Any previous step or needed job failed. |
| `always()` | Always, even after a failure. Also runs if the run was cancelled. |
| `cancelled()` | The workflow run was cancelled. |
jobs:
test:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- id: tests
run: npm test
- name: Upload report on failure
if: failure()
uses: actions/upload-artifact@v4
with:
name: test-report
path: reports/
- name: Cleanup
if: always()
run: echo "Cleaning up"Common errors
- Condition on a skipped dependency. If a job in
needsis skipped, the dependent job is skipped too, unless itsifincludes a status function such asalways(). - Forgetting the default. Writing
if: github.ref == 'refs/heads/main'alone still impliessuccess(). If you add a status function, you replace that implicit check, so combine them yourself. - Quoting problems. A YAML value that starts with
${{or contains:can break parsing. Wrap the whole expression in quotes when in doubt. - Comparing strings loosely. Comparisons in expressions are case-insensitive for strings. Use
==against the exact context value, such asgithub.event_name.
Flow of a decision
Exercise
A cleanup step must run after the tests, whether they pass or fail, but it should not run if someone cancels the workflow run. Which if expression should you use?
Show answer
if: success() || failure(). It is true after either outcome, and false when the run is cancelled. Using always() would also run the step after a cancellation.
Exercise
A job has needs: test and if: github.ref == 'refs/heads/main'. The test job fails on main. Does the job run?
Show answer
No. Without a status function, the condition implicitly includes success(), and a needed job failed. To run it anyway, add failure() or always() to the expression.