This is Part 2 of setting up Gitlab continuous integration builds on Jenkins. Please follow Part 1 if you haven't done so already (part 1 details the initial config of Gitlab and Jenkins for CI).

In this article we're going to setup Gitlab and Jenkins to perform builds for every merge request. Basically we'll be performing CI for every review. Woot!

A build for every review

The image below is what we'll accomplish: excellent communication between the developer and tools. When a merge request is created for the devel branch, a Jenkins job is triggered; that job creates the Gitlab pipeline, causing the nice "Merge When Build Succeeds" button. Said another way, all changes are verified (code quality, unit tests, etc) automatically without a human.

Jenkins: Create the Jenkins pipeline job

The merge requests will be performed by a pipeline job. I'm assuming that you're using my ljdelight/thrifty fork because it already has Jenkinsfiles. Since we'll have two jobs per project, create a folder named thrifty .

Create a pipeline job named thrifty-reviews under the thrifty folder. Under build triggers, check "Build when a change is pushed to GitLab" and configure it similar to the image below. There's a small bug with the plugin key generation so Save or Apply the changes to the job first, then under 'Advanced...' generate a key. Gitlab requires this key.

Next add the below code to the Pipeline script section. This code is generic and is required because the project's Jenkinsfile can't be executed until the source is pulled... so we pull the source here and start execution at Jenkinsfile.common .

node() { try { // Pull the source and test a merge checkout changelog: true, poll: true, scm: [ $class: 'GitSCM', branches: [[name: "origin/${env.gitlabSourceBranch}"]], doGenerateSubmoduleConfigurations: false, extensions: [[ $class: 'PreBuildMerge', options: [ fastForwardMode: 'FF', mergeRemote: 'origin', mergeStrategy: 'default', mergeTarget: "${env.gitlabTargetBranch}" ] ]], submoduleCfg: [], userRemoteConfigs: [[ credentialsId: 'gitlab-jenkins-user-credentials', name: 'origin', url: "${env.gitlabSourceRepoHttpUrl}" ]] ] // Start the build load "Jenkinsfile.common" } catch (Exception e) { updateGitlabCommitStatus(name: 'build', state: 'failed') addGitLabMRComment comment: "Something unexpected happened. Inspect Jenkins logs." throw e } }

Gitlab: Add webhook to start Jenkins pipeline

Back in Gitlab, go to the project's settings and Webhooks . Add a webhook to your URL (mine is http://jenkins-master:8080/project/thrifty/thrifty-reviews ) using your secret token. Disable ssl verification, and under triggers select: Comments, Merge Request Events. Push test and it should complete successfully.

Test it out

Merge requests will now trigger CI builds! Try it out by creating a branch and starting a merge request. You can even type "Jenkins rebuild please" in the MR discussion to cause a rebuild.