Skip to content
Latchkey

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.sh

Gotchas

  • Pair the branch gate with a protected environment for real enforcement, since if alone is a convention.
  • On pull_request events use github.head_ref, not github.ref.

Related guides

Run this faster and cheaper on Latchkey managed runners. Start free →