Kimbriel Oraya
Kimbriel Oraya

Reputation: 49

CI pipeline run only when Merge Request has new push commit and to specific branch

I want to create a pipeline that only run when have merge request to specific branch and also it can run every time working branch has new push commit.

this is my example but it wont work properly:

unit_test:
stage: test
script:
 - echo "unit test running"
only:
 - merge_requests
 - develop
 - push

Upvotes: 1

Views: 3901

Answers (2)

Kimbriel Oraya
Kimbriel Oraya

Reputation: 49

using Gitlab CI workflow and Gitlab CI rules make what i want to do.

image: ...

workflow:
  rules:
    - if: '$CI_COMMIT_BRANCH' # All branches
    - if: '$CI_PIPELINE_SOURCE == "merge_request_event"' # Merge requests
    - if: '$CI_COMMIT_BRANCH && $CI_OPEN_MERGE_REQUESTS' # Fix detached merge request pipelines
      when: never

Upvotes: 0

Reza Ebrahimpour
Reza Ebrahimpour

Reputation: 914

When working with merge requests, you need to use workflow and rule to control how the runner should trigger the pipelines. You can read more about them on Gitlab's official documentation: Gitab CI workflow and Gitlab CI rules

Using workflow, you can control the execution of stages generally, and using rules you can control the execution of a specific stage. You can use Predefined Variables or even custom variables to write some rules.

For instance, in the following sample, the runner will trigger the pipeline if there is a push over branches and when a merge request is created. It will also disable branch pipeline when you push to a branch when there is an open merge request.

image: ...

workflow:
  rules:
    - if: '$CI_COMMIT_BRANCH' # All branches
    - if: '$CI_PIPELINE_SOURCE == "merge_request_event"' # Merge requests
    - if: '$CI_COMMIT_BRANCH && $CI_OPEN_MERGE_REQUESTS' # Fix detached merge request pipelines
      when: never

And in the following example, you can limit the execution of a stage by the name of the source and destination branches in the merge request.

job:
  script: echo "Hello, Rules!"
  rules:
    - if: '$CI_MERGE_REQUEST_SOURCE_BRANCH_NAME =~ /^feature/ && $CI_MERGE_REQUEST_TARGET_BRANCH_NAME == $CI_DEFAULT_BRANCH'
      when: always
    - if: '$CI_MERGE_REQUEST_SOURCE_BRANCH_NAME =~ /^feature/'
      when: manual
      allow_failure: true

Upvotes: 4

Related Questions