Skip to content
Latchkey

How to Use rules:if for Branch Pipelines in GitLab CI

rules:if matches CI variables so you decide exactly which branches and events a job runs on.

The modern way to gate jobs in GitLab is rules:if with predefined variables like CI_COMMIT_BRANCH and CI_PIPELINE_SOURCE. Each rule can also set when and variables.

Run on main, on MRs, and skip otherwise

Order rules from most to least specific; the first match wins.

.gitlab-ci.yml
test:
  script: ./run-tests.sh
  rules:
    - if: '$CI_PIPELINE_SOURCE == "merge_request_event"'
    - if: '$CI_COMMIT_BRANCH == $CI_DEFAULT_BRANCH'

deploy:
  script: ./deploy.sh
  rules:
    - if: '$CI_COMMIT_BRANCH == "main"'
      when: on_success
    - when: never

Notes

  • A trailing - when: never makes the intent explicit so the job never runs outside the listed conditions.
  • rules: replaces the older only/except keywords and should not be combined with them in the same job.

Related guides

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