Categories
Java Software development

Jenkins Multibranch Pipeline

Use the Jenkins Multibranch Pipeline to automate your build process and execute the build on all branches in the repository. Create a Jenkinsfile in your source that describes the steps of the build process.

jenkins-logoI recently upgraded Jenkins (https://jenkins.io) to the 2.0 version and had to setup all the jobs again. It is quite a manual process and I wonder if this can be automated in some way.

Gradle plugin

There exists a Gradle plugin (a plugin to use in a Gradle build script) to automate setting up a Jenkins server, see https://github.com/ghale/gradle-jenkins-plugin/wiki. This solution automates the one-time process of setting up jobs. I find this approach interesting, although a bit too much at this point.

Multibranch Pipeline jobs

In the Jenkins 2.0 version, I noticed Multibranch Pipeline jobs – these jobs get most of their configuration from a script that you put in the source repository. This is a great solution, since you can version the configuration and don’t have the manually enter at the Jenkins user interface. Another great feature is that a multibranch pipeline scans your Git repository for branches and builds all of those branches automatically.

option-multibranch

The way you configure a Multibranch Pipeline is by configuring the repository and how the build is triggered. The easiest way is to trigger periodically. That is all the configuration that you enter on the Jenkins user interface.

Selection_031

After this configuration, Jenkins will look at all your branches in the repository and look for a file in the root with the name “Jenkinsfile”. This file should contain a Groovy script that performs the build.

node {
 checkout scm
 sh "./gradlew clean build"
}

This script will checkout the branch from the repository and execute “./gradlew clean build”. After you added this file to your repository, you can manually trigger Jenkins with Build Indexing/Run Now. You will will see a list with all the branches that have a Jenkinsfile.

jenkins-branch-master

 

 

This is great if you want to make sure that the code that is committed the repository actually compiles.

To take a step further, you probably want to run your unit tests and show the results. You can just use the “test” task:

node {
 checkout scm
 sh "./gradlew clean test"
}

This will run the build and test in one step. To make a clearer overview of the whole process, you can defines stages and impose timeouts:

node {
 stage 'checkout'
 checkout scm

stage 'build'
 timeout(time: 15, unit: 'MINUTES') {
 sh "./gradlew clean build"
 }

stage 'test'
 timeout(time: 15, unit: 'MINUTES') {
 sh "./gradlew test"
 }
}

This will produce a nice report of all the stages.

jenkins-stages

Now you can quickly see how long each stage took and if it is successful.

It would also be nice to show the results of the tests, and I will explore that in another post.