Create a Declarative Pipeline Jenkinsfile for Maven Releasing

I recently tried to create a Jenkins job to build and — occasionally — release a Java library via Maven using the declarative pipeline syntax (for I like its legibility and how it keeps us from doing stupid things). It turned out that this is not exactly trivial for various reasons.

Build on Commit, Release on Demand

I decided to solve this with a parameter RELEASE whose default setting is false:

parameters {
booleanParam(
name: "RELEASE",
description: "Build a release from current commit.",
defaultValue: false)
}

Now I can add a when directive to my release stage to prevent it from being executed if the parameter is not set to true:

when { expression { params.RELEASE } }

So my Jenkinsfile looks like this:

Note that this is for a single branch job. If you build for multiple branches, you might want to restrict releases to your master branch by using a when declaration like this:

when {
allof {
branch "development"
expression { params.RELEASE }
}
}

Executing for a build worked just fine. However trying to release gave me this error:

[ERROR] Failed to execute goal org.apache.maven.plugins:maven-release-plugin:2.5.3:prepare (default-cli) on project date-time-test-support: An error is occurred in the checkin process: Exception while executing SCM command. Detecting the current branch failed: fatal: ref HEAD is not a symbolic ref -> [Help 1]

Checkout to local Branch

To fix this you simply need to change that behavior, forcing Jenkins to checkout to a local branch. To do this we need to change the Seedjob: from

scm { git("...", "*/master") }

to

scm {
git {
remote {
url("...")
branch("*/master")
}
extensions {
localBranch("master")
}
}
}

My seedjob.groovy then looked like this:

This made the release build pass flawlessly. Artifactory received the artifact and Git got the new pom.xml and the tag pushed.

I've been a software engineer since 2009, worked in various agile projects & got a taste for quality assurance. Today I'm a quality engineer at REWE digital.

I've been a software engineer since 2009, worked in various agile projects & got a taste for quality assurance. Today I'm a quality engineer at REWE digital.