Gitlab run a pipeline job when a merge request is merged

Viewed 12745

I have a gitlab pipeline where there are two stages, one is build and the other one is deploy. The build stage is run when a commit is made. I want a way to run the deploy job when the merge request is merged to master. I tried several things but no luck. Can anyone help?

stages:
  - build
  - deploy

dotnet:
script: "echo This builds!"
stage: build


production:
script: "echo This deploys!"
stage: deploy

only:
  refs:
    - master
2 Answers

Try using the gitlab-ci.yml "rules" feature to check for the merge request event.

Your current gitlab-ci.yml will run your "dotnet" job every commit, merge request, schedule, and manually triggered pipeline.

https://docs.gitlab.com/ee/ci/yaml/#workflowrules

dotnet:
  script: "echo This builds!"
  stage: build
  rules:
    - if: '$CI_COMMIT_REF_NAME != "master" && $CI_PIPELINE_SOURCE == "push" || $CI_PIPELINE_SOURCE == "merge_request_event"'

production:
  script: "echo This deploys!"
  stage: deploy
  rules:
    - if: '$CI_PIPELINE_SOURCE == "push" && $CI_COMMIT_REF_NAME == "master"'

If you want your job run on only after merging the merge request, then you can trigger a job based on the commit message, as shown below.

rules:
    - if: '$CI_COMMIT_MESSAGE =~ /See merge request/'

Basically, all the merge request comes with a "See merge request" commit message so you can depend on that message to trigger your job.

Related