How to Gate a Deploy on the Branch With an if in GitHub Actions
A job-level if on github.ref stops a deploy job from ever running on a non-release branch.
Guard the deploy job with if: github.ref == 'refs/heads/main' and needs: test, so it only runs after tests pass on the release branch.
Steps
- Keep build and test jobs unconditional.
- Add
needs:on the deploy job so it waits for tests. - Add
if: github.ref == 'refs/heads/main'at the deploy job level.
Workflow
.github/workflows/ci.yml
jobs:
test:
runs-on: ubuntu-latest
steps:
- run: npm test
deploy:
needs: test
if: github.ref == 'refs/heads/main'
runs-on: ubuntu-latest
environment: production
steps:
- run: ./deploy.shGotchas
- Pair the branch gate with a protected environment for real enforcement, since
ifalone is a convention. - On
pull_requestevents usegithub.head_ref, notgithub.ref.
Related guides
How to Run a Job Only if a Condition Is True in GitHub ActionsGate an entire GitHub Actions job with a job-level if so every step is skipped when the condition is false, u…
How to Run a Step Only on the Main Branch in GitHub ActionsRestrict a GitHub Actions step to the main branch by checking github.ref against refs/heads/main, so branch-s…