简体   繁体   English

如何将Jenkins环境变量注入maven构建?

[英]How to inject Jenkins environment variable into maven build?

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. 我需要获取一些Jenkins环境变量,如BUILD_NUMBER和BUILD_URL,并将它们作为变量注入我的Maven Java构建中。

I have added this to the pom.xml 我已将此添加到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 在使用mvn install进行构建时,我正在尝试获取变量

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

but unfortunately the result is null... 但不幸的是结果是空的......

What I'm doing wrong guys? 我做错了什么?

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: 然后你必须配置surefire插件的环境变量:

<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 如本文档中所述: 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. 请注意,可以在其他插件中执行相同操作,例如Maven Tomcat插件。

This how I achieved this in my application 这是我在我的应用程序中实现的方法

Add a property in pom.xml 在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 在.properties文件中创建一个新属性

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

Enable filtering in maven by adding 通过添加启用maven中的过滤

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

Then read it from java using the following code 然后使用以下代码从java中读取它

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} 将maven目标更改为clean package -Denv.BUILD_NUMBER = $ {BUILD_NUMBER}

I was displaying this in our application's about page. 我在我们的应用程序中显示了这个页面。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM