Search code examples
mavenjenkins

Getting Project Version from Maven POM in Jenkins


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!


Solution

  • 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.