How to inject Jenkins environment variable into maven build?

16,581

Solution 1

Guessing you are trying to read this value into your unit tests? Then you would have to configure the environment variables of the surefire plugin:

<plugin>
   <groupId>org.apache.maven.plugins</groupId>
   <artifactId>maven-surefire-plugin</artifactId>
   <configuration>
       <environmentVariables>
           <jenkins.buildUrl>${env.BUILD_URL}</jenkins.buildUrl>
       </environmentVariables>
   </configuration>
</plugin>

As stated in this documentation: http://maven.apache.org/surefire/maven-surefire-plugin/test-mojo.html#environmentVariables

Note that it's possible to do the same in other plugin, like the Maven Tomcat Plugin for example.

Solution 2

This how I achieved this in my application

Add a property in pom.xml

<properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>      
    <jenkins.buildNumber>${env.BUILD_NUMBER}</jenkins.buildNumber>      
</properties>

Create a new property in .properties file

jenkins.build.number = ${jenkins.buildNumber}

Enable filtering in maven by adding

<resources>
    <resource>
        <directory>src/main/resources</directory>
        <filtering>true</filtering>
    </resource>
</resources>

Then read it from java using the following code

properties.load(MyClass.class.getResourceAsStream("/project.properties"));
version = properties.getProperty("jenkins.build.number");

Change the maven goal as clean package -Denv.BUILD_NUMBER=${BUILD_NUMBER}

I was displaying this in our application's about page.

Share:
16,581
Atanas Kanchev
Author by

Atanas Kanchev

Hoho

Updated on June 18, 2022

Comments

  • Atanas Kanchev
    Atanas Kanchev almost 2 years

    I need to get some of the Jenkins environment variables like BUILD_NUMBER and BUILD_URL and to inject them as variables in my Maven Java build.

    I have added this to the pom.xml

    <properties>
        <jenkins.buildUrl>${env.BUILD_URL}</jenkins.buildUrl>
    </properties>
    

    and while building with just mvn install I'm trying to get the variable by

    private static final String JENKINS_BUILD_URL = System.getProperty("jenkins.buildUrl");
    

    but unfortunately the result is null...

    What I'm doing wrong guys?