Karias Bolster
Karias Bolster

Reputation: 1035

Run GitlabCI during Merge Request and After Merge

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.

Upvotes: 20

Views: 34115

Answers (4)

ThePsyjo
ThePsyjo

Reputation: 59

For recent versions of GitLab you want to use the following syntax as only and except, mentioned by Philipp Ludwig (answer), are deprecated.

before merge

rules:
  - if: $CI_COMMIT_BRANCH != "main"

after merge

rules:
  - if: $CI_COMMIT_BRANCH == "main"

Upvotes: 0

Odysseu
Odysseu

Reputation: 11

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

Upvotes: 1

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

Upvotes: -3

Philipp Ludwig
Philipp Ludwig

Reputation: 4190

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

Upvotes: 19

Related Questions