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: neverNotes
- 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
How to Run a Job Manually with Input Variables in GitLab CITrigger a GitLab CI job by hand and let the operator supply values using a manual when:manual job plus pre-fi…
How to Deploy to AWS with OIDC in GitLab CIAuthenticate GitLab CI to AWS without long-lived keys by exchanging the GitLab ID token for temporary credent…