Home > maven > Getting Maven Version in Jenkins

Getting Maven Version in Jenkins

March 27Hits:17

Is there any way a Jenkins build can be aware of the Maven version number of a project after processing the POM?

I've got some projects where versioning is controlled by Maven, and in a post-build job we'd like to create a Debian package and call some shell scripts. What I need is for the version number that Maven used to be available as a Jenkins environment variable so I can pass it to post-build actions.

To be clear, I'm not needing to know how to get Jenkins to pass a version number to Maven; instead I want Maven to pass a version number to 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:


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));

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.

We used the Groovy Postbuild Plugin.

    String regex = '.*\\[INFO\\] Building .+ (.+)';
    def matcher = manager.getLogMatcher(regex);
    if (matcher == null) {
        version = null;
    } else {
        version =  matcher.group(1);

Adding this to Jenkins for use later is a bit tricky. Give this a shot, although I remember this causing us some headaches. (Sorry, we did this a long time ago)

def addBuildParameter(String key, String value) {
    manager.build.addAction(new hudson.model.ParametersAction(new hudson.model.StringParameterValue(key,value)));

Execute the Maven Plugin "exec-maven-plugin" in "Execute Shell" as a "Conditional step" worked for me:

mvn -q -Dexec.executable="echo" -Dexec.args='${projects.version}' --non-recursive org.codehaus.mojo:exec-maven-plugin:1.3.1:exec

Integrate in Jenkins:

-> "Add post-build step"
    -> "Conditional steps (single or multiple)"
        -> "Execute Shell:"

export MY_POM_VERSION=`mvn -q -Dexec.executable="echo" -Dexec.args='${projects.version}' --non-recursive org.codehaus.mojo:exec-maven-plugin:1.3.1:exec` && [[ "${MY_POM_VERSION}" == "THE_VERSION_TO_BE_MATCHED" ]] && echo "CONDITION_IS_MET"

    -> "Steps to run if condition is met"
        -> Add any build step you need


  • THE_VERSION_TO_BE_MATCHED has to exchanged with your version
  • '&& echo "CONDITION_IS_MET"' is only for debugging purposes. For the same purpose you can add a '&& echo "MY_POM_VERSION=${MY_POM_VERSION}"' after the mvn command in order to understand what's going on.

This approach is more reliable than a "grep" and it could be an alternative if the Jenkins Ruby Plugin is not installed.

Had the same need and solved as suggested with Groovy parsing the pom.

import jenkins.util.*;
import jenkins.model.*;

def thr = Thread.currentThread();
def currentBuild = thr?.executable;
def workspace = currentBuild.getModuleRoot().absolutize().toString();

def project = new XmlSlurper().parse(new File("$workspace/pom.xml"))

def param = new hudson.model.StringParameterValue("project.version", project.version.toString())
currentBuild.addAction(new hudson.model.ParametersAction(param));

Add this script as a post step of type "Execute system Groovy script" (so it's not needed to install Groovy) and paste the code in the "Groovy command".

You could also do :

MAVEN_VERSION=`grep A -2 -B 2 "<your_project_name>" pom.xml | grep version | cut -d\> -f 2 | cut -d\< -f 1`-commit-"`echo $GIT_COMMIT`"

Explanation: assuming that you have your project name within a line or two above/below version like a normal pom:


Then you can easily grep for the artifactId, use the "before/after" grep actions to suck in the version with it, and then grep the version out and use the simple unix "cut" command to splice out the content between "version" tags.

I like the Jenkins-groovy integration, but this is alot easier and will work even on a build server which you dont have control over (i.e. because bash is universal).

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.

Related Articles

  • Getting Maven Version in JenkinsMarch 27

    Is there any way a Jenkins build can be aware of the Maven version number of a project after processing the POM? I've got some projects where versioning is controlled by Maven, and in a post-build job we'd like to create a Debian package and call som

  • `class file has wrong version` after Jenkins upgradeJanuary 18

    A couple of days ago, I upgraded Jenkins to version 1.643. Before, we were using Jenkins 1.593. Starting with Jenkins 1.612, Jenkins requires Java 7, see changelog, announcement and issue. Our Jenkins server has Java 8. I have a Maven project consist

  • How to update maven version on ubuntu machine?September 20

    I am working on Ubuntu linux machine. When I open a terminal window and type : mvn -v I got the output: Apache Maven 2.2.1 (rdebian-1) Java version: 1.6.0_26 Java home: /usr/lib/jvm/java-6-sun- Default locale: en_US, platform encoding: UT

  • How to install a newer version of Jenkins on 12.04 LTS?December 13

    I'm on Ubuntu 12.04 and I need to install a version of Jenkins greater than the one provided in the Ubuntu repositories (1.424.6). Specifically I at least need version 1.426 (I want to use API tokens for an external script), but I would like to have

  • Maven interfering with Jenkins post build scriptOctober 4

    I have a Jenkins Maven job that has a post build script written in BASH. Periodically, while the post script is running, it seems like some sort of Maven operation is interfering with the BASH script causing the build to fail. Here's some sample outp

  • Error "Could not transfer metadata" running Maven deploy with JenkinsJanuary 29

    I have 2 Maven projects, which are deployed daily in a Nexus snapshots repository by Jenkins builds. For one project, everything works fine. For the second one, I have the error below every time Jenkisn runs mvn deploy : [INFO] --- maven-deploy-plugi

  • Getting the current release version from Jenkins and pass it as a parameter

    Getting the current release version from Jenkins and pass it as a parameterFebruary 8

    I am new to DevOps and Jenkins and I want to ask you something. I'll try to simply explain my need hoping for helpful suggestions from you, so here we start : To Perform a Maven Release, I need to specify the version of the current release in my pom.

  • Update Maven version in Ubuntu 8.1March 11

    My ubuntu has maven 2.0.9 version installed, but now i want to update to the newest version. Altough Im not the root, I have downloaded maven latest version, modified the M2_HOME in .bashrc file with sudo, but when i type in console mvn -version, the

  • Code Analysis & Reporting: Maven vs. JenkinsSeptember 27

    My team (~10 devs) has recently migrated to Maven (multi-module project, ca. 50 modules) and we now use Jenkins for continuous integration. As the overall setup is running, we are planning to include code analysis and reporting tools (e.g., Checkstyl

  • Switch Maven version after installing from jpackage?June 6

    I've installed maven3 on CentOS from the JPackage repository. Problem is my installs also seem to have pulled in maven2 which is the default. Is there any way to switch /usr/bin/mvn to be maven3? perhaps using the alternatives application? (note: I c

  • How can I generate incremental Maven build in Jenkins Job DSL?February 9

    I'm trying to generate what appears in my Jenkins Maven job under Advanced... as Incremental build - only build changed modules This is an XML node that's directly within <maven2-moduleset>. I didn't find it in the API, so I thought I'd use configur

  • How to run a single module in a multimodule maven Project through jenkinsFebruary 9

    I have created integration tests as a maven multi module project. Each module represents an integration tests. When I do a build on jenkins it runs all the test , I couldnt find the option to run a single module ( in my case a test).

  • Cannot change maven version in eclipseJanuary 10

    After failing to mvn package inside of eclipse but succeeding in the terminal, I realized that eclipse was running maven 3.3.3 while terminal was running 3.3.9. I attempted, and by all apparent accounts succeeded, to reconfigure eclipse by going to E

  • Get variable of maven job in jenkins-workflowJanuary 22

    I have a maven project that I trigger with workflow plugin: build job: 'maven_project' Now i want to access the variable POM_VERSION set in that job. I tried it through buildVariables but that does not seem to work as i get null: result = build job:

  • git, maven and jenkins - versioning, dev and release builds workflowMarch 29

    What is the preferred way to do the following with git, maven and jenkins: I am developping an application, which I would like to maintain "dev" and "release" branches. I would like jenkins to build both. It could be so that the releas

  • Jenkins maven java 7 permission issueJanuary 29

    I'm getting this error when attempting a Maven build in Jenkins, Building in workspace /var/lib/jenkins/workspace/xxxxprojectnamedeletedforprivacyxxxx java.nio.file.AccessDeniedException: /usr/share/maven/lib/maven-settings-3.x.jar at sun.nio.fs.Unix

  • Conventions for revision control with Maven/JenkinsApril 21

    For a software project I am working on, we have a 'dev => QA => production' methodology. That is, we create a release candidate (deployed to Artifactory), give it to QA (deploy to QA systems and a QA backend/application server) who takes a week or s

  • Increment version in every Jenkin's build and update dependenciesJanuary 18

    I have a number of Maven projects being built my Jenkins server. These projects have dependencies on each other, e.g. service-base -> java-base -> pom-base In other words, the Maven project service-base depends on the Maven project java-base. Natura

  • Maven 3 warnings about build.plugins.plugin.versionNovember 8

    Since I updated to Maven 3 I get the following warning messages at each build : How can I get rid of these warnings? [INFO] Scanning for projects... [WARNING] [WARNING] Some problems were encountered while building the effective model for proj:id:jar

  • Out of memory expection after migrating to maven latest version 3.3.9January 31

    I have migrated maven version 3.0.1 to 3.3.9. when I am trying to do maven build I am getting the java heap size out of memory exception. If I increasing memory size to 8192 build will get success. But I donot want to increase my memory size and want

Copyright (C) 2017 ceus-now.com, All Rights Reserved. webmaster#ceus-now.com 14 q. 0.463 s.