How to Run Merge Request Pipelines in GitLab CI/CD
A merge request pipeline runs in the MR context and exposes MR variables, which branch pipelines do not.
Add rules:if: $CI_PIPELINE_SOURCE == "merge_request_event" so the job runs in MR pipelines, and avoid duplicate branch-plus-MR pipelines by structuring rules carefully.
Steps
- Add a rule matching
$CI_PIPELINE_SOURCE == "merge_request_event". - Read MR context via
$CI_MERGE_REQUEST_*variables. - Add a branch rule too if you also want branch pipelines, avoiding duplicates.
Pipeline
.gitlab-ci.yml
test:
script: npm test
rules:
- if: '$CI_PIPELINE_SOURCE == "merge_request_event"'
- if: '$CI_COMMIT_BRANCH == "main"'Gotchas
- Without an MR rule, a job never runs in merge request pipelines and
$CI_MERGE_REQUEST_*stays empty. - Matching both branch and MR sources can create duplicate pipelines; use
workflow:rulesto pick one.
Related guides
How to Use rules for Conditional Jobs in GitLab CI/CDControl when a GitLab CI/CD job runs with rules, combining if conditions, changes filters, and when to add, s…
How to Create Review Apps in GitLab CI/CDSpin up a per-merge-request review app in GitLab CI/CD with a dynamic environment name and an on_stop job tha…