18

How can I make GitLab CI run on merge request and after merge?

Two branches, dev and master. Two jobs, test and deploy.

On merge request from any branch to dev branch, CI will trigger. But I only want the test job to run for now. And when the merge request is merged it will then proceed to execute the deploy job. The reason being like this is, although all the tests will pass, we still can't proceed with the deployment because there might be some comments from validators in the Code Review that the dev will need to address. Only after addressing those comments and then if the unit tests are successful will then it be allowed to be merged. After the merge request have been merged, only then will it allow to deploy. The dev branch will be deployed to dev/test and master will be deployed to staging. Prod will be deployed manually.

Karias Bolster
  • 955
  • 3
  • 17
  • 31

3 Answers3

17

Use the only and except syntax to define the different jobs. If you are merging to your master branch, you could create a job called before-merge with the following syntax:

before-merge:
  except:
  - master

Then, your deploy job runs only for commits to the master branch:

deploy:
  only:
  - master

This way, the before-merge job should be executed for commits on all branches except master, and the deploy job will only be executed after the merge to the master branch occurred.

Reference: https://docs.gitlab.com/ce/ci/yaml/README.html#only-and-except-simplified

Philipp Ludwig
  • 3,758
  • 3
  • 30
  • 48
  • 3
    I get the idea and after reading the link i still couldn't implement what I wanted. The whole flow of the CI is on merge request, it will run the test job and after merging the merge request, it will then run the deploy job. – Karias Bolster Jul 23 '18 at 10:26
  • GitLab runs the pipeline automatically for every merge request and after a merge, since every commit triggers the pipeline - where does it fail for you? – Philipp Ludwig Jul 23 '18 at 13:11
  • @PhilippLudwig: How about if I want to run the deploy job only when the merge request is merged but not when the merge request created – Minh Nguyen Sep 08 '19 at 03:03
  • @MinhNguyen It’s the same thing, just run your pipeline only for your main branch (e.g. `master`). – Philipp Ludwig Mar 04 '20 at 11:48
1

You need to parse the merge event.

The variables available after a merge are premium only says doc here : https://docs.gitlab.com/ee/ci/pipelines/merged_results_pipelines.html

However,

  • protecting main (or master branch) to MR only
  • and
  • triggering the after-merge pipeline on push to main (or master)

will do the trick

Odysseu
  • 11
  • 3
-2

You can also checkout this answer, because gitlab provided some predefined variables for this type of scenarios.