I have a Gitlab pipeline based on a .gitlab-ci.yml file. I want to trigger my pipeline when a merge request is created that merges any branch into the "main" branch. My current .gitlab-ci.yml code triggers the pipeline on any merge request or manual trigger and looks like this:
build:
rules:
- if: '$CI_PIPELINE_SOURCE == "merge_request_event"'
when: always # triggers pipeline on merge request
- if: '$CI_PIPELINE_SOURCE == "web"'
when: always # triggers pipeline via web UI "Run pipeline" button
- when: never # does not trigger pipeline on other events
But when I add a condition to the first "if:" to only trigger on a merge into "main" based on online examples, my pipeline does not trigger anymore. I tried two options:
Option 1:
build:
rules:
- if: '$CI_PIPELINE_SOURCE == "merge_request_event" && $CI_COMMIT_BRANCH == $CI_DEFAULT_BRANCH'
when: always
- if: '$CI_PIPELINE_SOURCE == "web"'
when: always
- when: never
Option 2:
build:
rules:
- if: '$CI_PIPELINE_SOURCE == "merge_request_event" && $CI_COMMIT_REF_NAME == "main"'
when: always
- if: '$CI_PIPELINE_SOURCE == "web"'
when: always
- when: never
The code is accepted and runs fine. But my pipeline does not trigger automatically anymore. Any help to answer my question is appreciated.
CI_COMMIT_BRANCH
is not available as a predefined CI variable during a merge request. You can use MR specific predefined variables during an MR, here is example using CI_MERGE_REQUEST_TARGET_BRANCH_NAME
See more about predefined CI vars here
Option 1: Default branch (is not always main
)
build:
rules:
- if: $CI_PIPELINE_SOURCE == "merge_request_event" && $CI_MERGE_REQUEST_TARGET_BRANCH_NAME == $CI_DEFAULT_BRANCH
when: always
- when: never
Option 2: Explicit main
build:
rules:
- if: $CI_PIPELINE_SOURCE == "merge_request_event" && $CI_MERGE_REQUEST_TARGET_BRANCH_NAME == "main"
when: always
- when: never