Sub topic 13
Combining triggers in one workflow
This chapter assumes you can write the on key in its map form and know the push, pullrequest, schedule and workflowdispatch events from the earlier chapters.
One file, several entry points
The on key accepts several events at once. The workflow starts when any of them occurs. Each event has its own filters, so a filter under push never affects pull_request.
name: CI
on:
push:
branches: [main]
pull_request:
branches: [main]
schedule:
- cron: '0 6 * * 1'
workflow_dispatch:
jobs:
test:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- run: echo "Event: ${{ github.event_name }}"
- name: Weekly-only step
if: github.event_name == 'schedule'
run: echo "Running the weekly extra checks"This workflow runs in four situations:
- A push to
main. - A pull request targeting
main. - Every Monday at 06:00 UTC.
- A manual start.
Branching on the event
Every run has a github.event_name value such as push, pull_request, schedule or workflow_dispatch. Use it in an if: condition to run a step or job for only some triggers. In the example, the weekly step is skipped on every other event.
What differs between events
The same file behaves differently depending on the trigger:
| Event | Code that is checked out | Notes |
|---|---|---|
| push | The pushed commit | Runs from the workflow file on that branch |
| pull_request | A merge of the PR and its base branch | Runs from the merge result |
| schedule | The latest commit on the default branch | Runs only from the default branch |
| workflow_dispatch | The branch you select | The file must exist on the default branch for the UI button to appear |
Inputs exist only for workflow_dispatch. In other runs, inputs.environment is empty, so write steps that cope with that or guard them with if:.
Common errors
- Duplicate runs. If
pushhas no branch filter andpull_requestis also listed, a commit pushed to a pull request branch starts two runs. Limitpushtomainand release branches, as above. - Misplaced filters. Putting
branchesat the top level ofonis invalid. It belongs under a specific event. - Assuming one context. Code that reads
github.event.pull_request.numberfails or returns nothing on a push. Checkgithub.event_namefirst. - Over-sharing secrets. A combined workflow that deploys should guard the deploy job with a condition, such as
if: github.event_name == 'push'. Otherwise a pull request or a scheduled run could deploy.
Exercise
A workflow lists push with no filters and pull_request for main. You push a new commit to a branch that has an open pull request to main. How many runs start, and how do you reduce them?
Show answer
Two runs start, one for push and one for pull_request. Add branches: [main] under push so that pushes to feature branches only trigger the pull_request run.