How to write a rule in Gitlab CI for running a job after merge to master?

Viewed 1732

I need to run a certain job on master branch after each merge to it. Pipelines that were scheduled or run manually should not contain this job. Is there a way to do that in GitLab CI?

As a side note, I want to say that I don't want to use "merge_request_event" because it triggers an additional pipeline after every commit to a merge request and it's something that doesn't suit me. But it will also run while triggering a pipeline on master manually and I don't need that

2 Answers

You can add this in you .gitlab-ci.yml file.

job_name:
  script:
    - your_job_part_1
    - your_job_part_2
  only:
    - master

It will run you job_name each time master is updated, hence, each time a merge request is accepted and branch is merged into master.

You can take a look at GitLab CI/CD for more options.

You can use rules keyword:

job_name:
  rules:
    - if: $CI_COMMIT_BRANCH == 'master' && $CI_PIPELINE_SOURCE == 'merge_request_event'

You can also replace master string by $CI_DEFAULT_BRANCH variable if you master/main branch is the default.

See: https://docs.gitlab.com/ee/ci/yaml/index.html#rules

Related