gitlabgitlab-ci

Running Gitlab CI/CD job on main branch but job should not run on MR from main to other branches


I have added gitlab CI/CD job which should run after a MR is merged to master.

Test:
  stage: test
  script:
    - echo "hello world"
  rules:
    - if: $CI_MERGE_REQUEST_SOURCE_BRANCH_NAME =~ /main|master/
    when: never
  - if: '$CI_COMMIT_REF_NAME == "main" && $CI_PIPELINE_SOURCE != "merge_request_event"'
    when: manual

This job runs on when a mr is merged to main. But the job is also running when a MR is there from main branch to another branch. How can I avoid this. Job should only run when a mr is merged to master.


Solution

  • Test:
      stage: test
      script:
        - echo "hello world"
      rules:
        - if: $CI_COMMIT_BRANCH == $CI_DEFAULT_BRANCH
          when: manual
    

    With the changes above it should be enough to identify that you are merging changes to main as a merge is a push event to the default branch. Using $CI_COMMIT_BRANCH rules out MR pipelines as it's only available on commits.