Luke P. Issac
Luke P. Issac

Reputation: 1591

How to configure GitLab CI Pipeline only on merge requests and that too only for specific branches?

I have following configuration for enabling pipeline on merge requests. I want this pipeline to run only on merge request to few specific branches only. For Ex: "release/some-xyz-branch" and "develop" branches. How to do it ?

test_job:
    stage: test
    only:
        - merge_requests
    script:
        - npm run test

I have tried adding the branch name after "- merge_requests" as follows but it is not working as expected.

test_job:
    stage: test
    only:
        - merge_requests
        - develop
        - release/some-xyz-branch
    script:
        - npm run test

Upvotes: 7

Views: 7814

Answers (2)

Saravanan Selvamohan
Saravanan Selvamohan

Reputation: 344

We can use the $CI_COMMIT_REF_NAME predefined environment variable in combination with only:variables to accomplish this behavior

test_job:
    stage: test
    only: [merge_requests]
    except:
      variables:
         - $CI_COMMIT_REF_NAME =~ /^docs-/
    script:
        - npm run test

Note: docs- represents refs/merge-requests/:iid/head

Upvotes: 0

Murli Prajapati
Murli Prajapati

Reputation: 9713

You can use variables along with refs to run the pipeline.

test_async:
  script:
    - echo "Test Async"
  only:
    refs:
      - merge_requests
    variables:
      - $CI_MERGE_REQUEST_TARGET_BRANCH_NAME == "develop" || $CI_MERGE_REQUEST_TARGET_BRANCH_NAME =~ /^release\/.*$/

test_db:
  script:
    - echo "Test db"
  only: 
    - master  

In above yaml, test_async will only run when merge request is created and the target branch is either develop or starts with release/. test_db will only run when commited to master.

Upvotes: 14

Related Questions