Tips and Tricks using a Jenkinsfile

This is a collection of random things we encountered when crafting Jenkinsfiles for different projects.

Use current Git branch in Jenkinsfile

Simply using git scm in our Jenkinsfile wasn’t enough to build the same branch as configured in the Jenkins job. (e.g. in multi branch builds)

stage('checkout') {
    steps {
        script {
            def gitCommit = checkout(scm).GIT_COMMIT
            checkout([
                    $class: 'GitSCM',
                    branches: [[name: gitCommit]],
                userRemoteConfigs: scm.userRemoteConfigs
        ])
    }
}

For more information please see the documentation about script.

However there is another caveat when using scripts. You have to approve them.

How to approve script snippets from a Jenkinsfile via the groovy script console?

def signature = 'method hudson.plugins.git.GitSCM getUserRemoteConfigs'
org.jenkinsci.plugins.scriptsecurity.scripts.ScriptApproval.get().approveSignature(signature)

Conditional steps in a Jenkinsfile

We had some conditional build steps like the following in our Jenkinsfile:

if (currentBuild.result == null) { // only green builds
    steps {
        archiveArtifacts '**/libs/*.jar'
    }
}

This isn’t allowed in the new pipeline syntax. Converting Conditional Build Steps to Jenkins Pipeline 

stage ('archive artifacts') {
    when {
        // only green builds
        expression { currentBuild.result == null }
    }
    steps {
        archiveArtifacts '**/libs/*.jar'
    }
}

Using a custom Docker container

Sometimes a vanilla container isn’t enough. The following example shows how to create your own build image on-the-fly:

agent {
    dockerfile {
        args  '-v $HOME/.gradle:/root/.gradle'
    }
}

We added git and node to the basic OpenJDK image:

FROM openjdk:8u151-jdk-alpine3.7

RUN apk add --update git
RUN apk add --update nodejs

Comments welcome… ;-)