Sub topic 6
Running on a Specific Event, Branch or Tag
This chapter assumes you know the structure of a workflow file (on, jobs, steps), the difference between a job and a step, and basic YAML. It also assumes you can read an if expression. Here you will use the github context to run a step only for a given event, branch or tag.
The github context fields that matter
Most deployment conditions read three values from the github context.
| Expression | Holds | Example value |
|---|---|---|
| `github.event_name` | The event that started the run | `push`, `pull_request` |
| `github.ref` | The full ref that triggered the run | `refs/heads/main`, `refs/tags/v1.2.0` |
| `github.ref_name` | The short branch or tag name | `main`, `v1.2.0` |
For a pull request, github.ref is the merge ref (refs/pull/12/merge), not the source branch name. Do not test it against refs/heads/... in pull request runs.
Filtering by event and branch
A workflow that listens to several events can give each step its own condition. In this example the preview step runs only for pull requests, and the publish step runs only for pushes to main.
name: CI
on: [push, pull_request]
jobs:
build:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Build
run: echo "Building"
- name: Deploy preview
if: github.event_name == 'pull_request'
run: echo "Deploying preview"
- name: Publish
if: github.event_name == 'push' && github.ref == 'refs/heads/main'
run: echo "Publishing"The publish condition checks both the event and the ref. Checking only github.ref would also match other events that run on main, such as a manual run or a scheduled run.
Tags
A push of a tag has github.ref starting with refs/tags/. Use startsWith to match any tag, or compare github.ref_name to a pattern you build yourself. To skip tag builds, negate the check. Because the expression begins with !, wrap it in ${{ }}, otherwise YAML reads the ! as a tag indicator and the file fails to parse.
steps:
- name: Skip release tags
if: ${{ !startsWith(github.ref, 'refs/tags/') }}
run: echo "Not a tag build"To run only on version tags, use the positive form: if: startsWith(github.ref, 'refs/tags/v').
Common errors
- Comparing the wrong ref form.
github.ref == 'main'is always false. Usegithub.ref == 'refs/heads/main'orgithub.ref_name == 'main'. - Using
github.ref_namewithout the event in mind. In a pull request run,ref_nameis something like12/merge. To read the source branch, usegithub.head_ref, which is set only for pull request events. - Forgetting the event check. A branch test alone also matches
workflow_dispatchandscheduleruns on that branch. - Putting
!first without wrapping. See the tag example above.
Exercise
You want a step to run only when a tag that starts with v is pushed. Write the if line, and say what github.ref would contain for a push to main.
Show answer
if: startsWith(github.ref, 'refs/tags/v'). For a push to main, github.ref is refs/heads/main, so the condition is false and the step is skipped.