Run gitlab-ci.yml only when merge request to master made

Viewed 15064

I am currently having my project in GitLab and Heroku. What I wanna do is as soon as I ask for merge request with my feature branch (let's call it crud-on-spaghetti), I want to automatically run the tests on this branch (npm test basically, using Mocha/Chai), and after they succeed, merge this crud-on-spaghetti with master, commit it and push it to origin/master (which is remote on GitLab) and after git push heroku master (basically, push it to the master branch in Heroku, where my app is stored). I have read several articles on GitLab CI and I think this is more suitable for me (rather than Heroku CI, because I do not have DEV and PROD instances).

So, as of now, I do this manually. And this is my .gitlab-ci.yml file now (which is not committed/pushed yet):

stages:
  - test
  - deploy

test_for_illegal_bugs:
  stage: test
  script:
    - npm test

deploy_to_dev:
  stage: deploy
  only:
    - origin master
  script:
    - git commit
    - git push origin master
    - git pull heroku master --rebase
    - git push heroku master

Hence, my questions is: What do I exactly need to write in .gitlab-ci.yml in order to automate all these "manipulations" (above)?

PS. And another (theoretical) follow-up question: how is GitLab-CI Runner triggered? For instance, if I want it to trigger upon merge request with master, do I do that using only: ... in .gitlab-ci.yml?

2 Answers

Restrict stages to Merge Requests:

To have your test stage only being executed when a Merge Request (MR) is opened, use

   only:
     - merge_requests

According to the Gitlab docs, you can further restrict this to only being executed for MRs with a certain target branch, e.g. only MRs for master

   only:
     - merge_requests
   except:
     variables:
       - $CI_MERGE_REQUEST_TARGET_BRANCH_NAME != "master"

This adds an exception for all target branches that are not master.

Or use rules: for that:

  rules:
    - if: '$CI_PIPELINE_SOURCE == "merge_request_event" && $CI_MERGE_REQUEST_TARGET_BRANCH_NAME == "master"'

Restrict stages to Branches:

As already mentioned by @marcolz, this is achieved by

   only:
     - master

to only execute the stage for pushes to the master branch.

Related