At this moment I defined a environment variable called GLOBAL_VAR with the value \'test\' under Manage Jenkins -> Configure System -> Global Properties. I have a shell script wh
You can use:
import jenkins.model.*
instance = Jenkins.getInstance()
globalNodeProperties = instance.getGlobalNodeProperties()
envVarsNodePropertyList = globalNodeProperties.getAll(hudson.slaves.EnvironmentVariablesNodeProperty.class)
newEnvVarsNodeProperty = null
envVars = null
if ( envVarsNodePropertyList == null || envVarsNodePropertyList.size() == 0 ) {
newEnvVarsNodeProperty = new hudson.slaves.EnvironmentVariablesNodeProperty();
globalNodeProperties.add(newEnvVarsNodeProperty)
envVars = newEnvVarsNodeProperty.getEnvVars()
} else {
envVars = envVarsNodePropertyList.get(0).getEnvVars()
}
envVars.put("FOO", "foo")
instance.save()
The solution was found here
Does anyone know how to access the Jenkins environment variables in groovy?
I can provide an example from a Jenkins job we use. The job is parameterized and provides the user with the ability to set many values, one of which is "InstallVersion" (default value is -1). Additionally, we set up an environment variable called "JENKINS_TRUNK_LABEL". I won't go into specifics about this job, but, here's how we refer to "JENKINS_TRUNK_LABEL" within a Groovy script.
if (InstallVersion == "-1")
{
InstallVersion = "$JENKINS_TRUNK_LABEL"
}
Here is an example of some working code:
import jenkins.model.*
nodes = Jenkins.instance.globalNodeProperties
nodes.getAll(hudson.slaves.EnvironmentVariablesNodeProperty.class)
envVars = nodes[0].envVars
envVars['MY_GLOBAL_PROPERTY']
Sources of my solution:
https://gist.github.com/johnyzed/2af71090419af2b20c5a
http://pghalliday.com/jenkins/groovy/sonar/chef/configuration/management/2014/09/21/some-useful-jenkins-groovy-scripts.html
Note to the "hard core" moderator that deleted my previous answer: I have spent quite a few hours searching on the Internet before finding the right solution, you shouldn't delete posts without knowing what is it really talking about. I find such behavior rather discouraging :(
in "Execute Groovy script" you can access global (and build) variables by:
def env = System.getenv()
println(env['GLOBAL_VAR'])