Getting Project Version from Maven POM in Jenkins Getting Project Version from Maven POM in Jenkins jenkins jenkins

Getting Project Version from Maven POM in Jenkins


You can use the ${POM_VERSION} variable, which was introduced with https://issues.jenkins-ci.org/browse/JENKINS-18272


After a lot of digging around (I never realised how poorly-documented Jenkins is!) I found a quite trivial solution.

  1. Install the Groovy plugin
  2. Add a Post Step to your Maven build of type Execute **system** Groovy script
  3. Paste in the following snippet of Groovy:

Script:

import hudson.model.*;import hudson.util.*;def thr = Thread.currentThread();def currentBuild = thr?.executable;def mavenVer = currentBuild.getParent().getModules().toArray()[0].getVersion();def newParamAction = new hudson.model.ParametersAction(new hudson.model.StringParameterValue("MAVEN_VERSION", mavenVer));currentBuild.addAction(newParamAction);

The build environment variable called MAVEN_VERSION will now be available for substitution into other post-build steps in the usual manner (${MAVEN_VERSION}). I'm using it for Git tagging amongst other things.


As other answers already pointed out, if you are using the Maven project type, you have access to the $POM_VERSION variable. But if you are not, you can use this sequence of steps (ugly but reliable). Doing it this way relies on the same version of maven to determine the pom version (while handling complex parent/child pom inheritance where <version> may not even be present for the child).

  1. Maven step with this goal:

    org.apache.maven.plugins:maven-help-plugin:2.1.1:evaluate -Dexpression=project.version -l version.log

  2. Shell step: (You may need to adjust the path to version.log depending on your hierarchy)

    echo "POM_VERSION=$(grep -v '\[' version.log)" > props.properties

  3. Inject Environment Variables step (Environment Injector Plugin):

    Properties File Path: props.properties

Now you can use $POM_VERSION as if this were a Maven project.

What this does: Uses maven to print out the version together with a mess of output, then greps out the mess of output leaving just the version, writes it to a file using properties file format and then injects it into the build environment. The reason this is better than a one-liner like mvn ..... | grep -v '\[' is that using a Maven step does not make assumptions about the installed maven versions and will be handled by the same auto-installation as any other maven steps.