How to set environment variable from a job and use it in next job in jenkins?

百般思念 提交于 2021-02-07 06:19:07

问题


I want to have a job to set the environment variable and use these environment variables in all the next jobs. How can I set environment variable through Jenkins ?


回答1:


Technically, you can't pass env variables from one job to the next, and I'm not aware of a plugin to do that out of the box.

There is a technique however. The idea is to create a properties file in the first job (e.g. exported.properties), add that file to the job artifacts, and then import this file via the EnvInject plugin in the second job.

This pre-supposes that you have some link between the first and second job, which is typically achieved with the Copy Artifact plugin, but a number of workflow-like plugins can help you as well.

For example, for creating the properties file, add a step "Execute shell", with e.g.

echo "# Saving some version properties
BUILD_VERSION=${BuildVersion}
BUILD_NODE_NAME=${NODE_NAME}
SOURCE_JOB=${JOB_NAME}
" > ${WORKSPACE}/BuildVersion.properties

Of course, you can use other build steps, e.g. Windows shell, groovy script, etc... each with their specific syntax of course.




回答2:


There are two ways to do depending on your usecase:-

1) EnvfilePlugin -

Install this plugin if your environment variables are constant and not changing on the fly/Dynamic then you can save them in a text file and give the oath of the file in Jenkins job Configuration page. Under Build Environment check Set environment variables through a file. give the path of that file here.

If the environment variable is created in the first job then again you can save all the environment variable in a file and browse it using the above method.

2) EnvInject plugin-

Install this plugin and go to job configuration paeg. Select "Prepare an environment for the run" and save the properties as mentioned by Patrice in the above answer, also specify the path of script and other details.




回答3:


You can make your downstream jobs parameterized (add parameters in the job configuration page), then trigger this jobs from an upstream Workflow job, the workflow script would be something like this:

build job: 'my-downstream-job', parameters: 
    [[$class: 'StringParameterValue', name: 'MY_VAR', value: 'Hello world!']]

Then you can use MY_VAR as desired in your my-downstream-job.



来源:https://stackoverflow.com/questions/32858376/how-to-set-environment-variable-from-a-job-and-use-it-in-next-job-in-jenkins

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