Is it possible to set environment variables on a groovy function
13,700
Yes, you can do this. Jenkins Pipeline stores its environment variables in a map named ENV
. Therefore, you can add additional key value pairs to this map for additional environment variables. This would be done in Groovy syntax via:
// syntax option one
env.key = value
// syntax option two
env['key'] = value
For your example, this would look like:
def function () {
env.NAME = value
sh "do something using these env vars"
}
Author by
hagits
Configuratio/Build manager. Works with: Perl, PowerShell, Bash, ANT. Tools: TeamCity, RTC, Jira, SVN, GIT, Synergy.
Updated on June 12, 2022Comments
-
hagits about 2 years
I know I can have an environment section on jenkins pipeline (declarative) for a stage. Like this:
stage('Name') { environment { NAME = value } steps { script { Do something using these env vars } } }
I want to write a groovy function, to define some env vars, and run something, and call it from a few pipelines. Something like:
def function () { environment { NAME = value } sh "do something using these env vars" }
Is it possible somehow?
(I know I can write
sh "ENV=value; some CMD"
but I have few variables, and it is less read-able).