gitlabsonarqubegitlab-ci

Gitlab-ci: if MR exist just trigger merge_request detach pipeline, if not trigger source branch pipeline. Those 2 pipelines shouldn't run in same time


I want to see sonar results in the MR(merge request) command section when I create a MR.

My main expectations:

I tried to do it with the below example stage. But when I pushed the commit to the source pipeline, while MR is exist for source branch. I still getting double pipeline. Detach and source pipelines are running and I don't want to see both in same time, plus except not working with rules configuration. How can I integrate except section with rules part.

This is my gitlab-ci stage:

deploy:
  stage: deployment
  when: manual
  rules:
    - if: '$CI_PIPELINE_SOURCE == "merge_request_event" && $CUSTOM_VARIABLE == "true" || $CUSTOM_VARIABLE == "true"'
  script:
    - ....
    - ....
  except:
    - tags
    - main

I also tried below rules, if one of them fit my condition don't run the other one. But it still trigger both pipelines.

deploy:
  stage: deployment
  when: manual
  rules:
    - if: '$CI_PIPELINE_SOURCE == "merge_request_event" && $CUSTOM_VARIABLE == "true"'
      when: on_success
    - if: '$CI_PIPELINE_SOURCE == "push" && $CUSTOM_VARIABLE == "true"'
      when: on_success
  script:
    - ....
    - ....
  except:
    - tags
    - main

Solution

  • Covered in workflow:rules examples, In this case, you can use the CI_OPEN_MERGE_REQUESTS variable to determine whether to run the pipeline for merge request or just the feature branch.

    If you use both [pipelines for merge requests and branch pipelines], duplicate pipelines might run at the same time. To prevent duplicate pipelines, use the CI_OPEN_MERGE_REQUESTS variable.

    Using workflow:rules you can do this for the entire pipeline, but the same principle can also be applied to individual jobs.

    workflow:
      rules:
        - if: '$CI_PIPELINE_SOURCE == "merge_request_event"'
        - if: '$CI_COMMIT_BRANCH && $CI_OPEN_MERGE_REQUESTS'
          when: never
        - if: '$CI_COMMIT_BRANCH'
    
    

    This means your pipeline will run: