Getting Project Version from Maven POM in Jenkins
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).
Maven step with this goal:
org.apache.maven.plugins:maven-help-plugin:2.1.1:evaluate -Dexpression=project.version -l version.log
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
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.
After a lot of digging around (I never realised how poorly-documented Jenkins is!) I found a quite trivial solution.
- Install the Groovy plugin
- Add a
Post Step
to your Maven build of typeExecute **system** Groovy script
- 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.
You can use the ${POM_VERSION} variable, which was introduced with https://issues.jenkins-ci.org/browse/JENKINS-18272
I used Pipeline Utility Steps plugin in a declarative pipeline job to get Maven version. In the example below I use script variable instead of environment variable, because that can be modified and passed between stages.
def TAG_SELECTOR = "UNINTIALIZED"
pipeline {
agent any
stages {
stage('Build') {
steps {
sh "mvn --batch-mode -U deploy"
script {
TAG_SELECTOR = readMavenPom().getVersion()
}
echo("TAG_SELECTOR=${TAG_SELECTOR}")
}
}
}
}
Note: You must approve the getVersion() method after creating the job in Manage jenkins > In-process Script Approval.
See also:
- readMavenPom documentation