Jenkins inject environment variable

混江龙づ霸主 提交于 2020-01-09 11:11:35

问题


In a Jenkins job I'm doing a couple of actions that reside in the pre-step build, such as executing a shell script. With the use of the Jenkins plugin "EnvInject" I want to inject environment variables into my maven build (Unit tests) so that those can be used inside my Java unit tests. Inside the shell script im doing something similar as:

echo "ip=$IP" >> unit-test.properties

While building Jenkins outputs the following:

[EnvInject] - Injecting environment variables from a build step.
[EnvInject] - Injecting as environment variables the properties file path 'unit-test.properties'
[EnvInject] - Variables injected successfully.

But the "ip" variable is not available inside my Java code (unit test). When I do a full print of both System.getProperties() and System.getenv() I do not see the "ip" enlisted.

Do I need to perform any special actions for maven to pass the variable to my Java code? Is something else wrong?

I'm pretty much stuck from this point onward, I do want to inject a key=value from a pre-step into my Java code.


回答1:


My solution:

Create a "Build a free-style software project".

  1. Jenkins > New Item > Build a free-style software project
  2. Add 1st step: Execute shell @ Build, and echo key=value pairs to a .properties file
  3. Add 2nd step: Inject environment variables, use the .properties file as defined in step 2
  4. Add 3rd step: Invoke top-level Maven targets

All custom environment variables are accessible with the key as defined in step #2. This was the only way I found to inject environment variables from shell to java.




回答2:


I had a similar requirement in my project, except my project was Maven. To use a variable value from jenkins to my java code, I used -DargLine="-DEnv=$Environment" inside "Build->Advanced->JVM Options". From my java code, I fetched the value of "Env" using System.getProperty(). FYI "Environment" is my Jenkins Variable, and "Env" is variable which is storing the value passed from jenkins into its variable(Environment) and fetched in java code using System.getProperty().



来源:https://stackoverflow.com/questions/31203816/jenkins-inject-environment-variable

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!