Jenkins global environment variables in a Jenkins file

How to call global environment variables in Jenkinsfile?
For example, if I have a variable -

name:credentialsId value:xxxx-xxxx-xxxxx-xxxxxxxxx 

How to use it in groovy script?

I tried ${credentialsId} , but that didn't work. It will simply give an error:

 java.lang.NoSuchMethodError: No such DSL method '$' found among steps [ArtifactoryGradleBuild, ........ 
+17
source share
5 answers

In the Jenkins file, you have an Environment Work that says:

The full list of environment variables available from Jenkins Pipeline is documented at localhost: 8080 / syntax / globals / enb,

The syntax is ${env.xxx} as in:

 node { echo "Running ${env.BUILD_ID} on ${env.JENKINS_URL}" } 

See also " Environmental Management .

How to pass global variables to a Jenkins file? When I say global variables - I mean

 Jenkins -> Manage Jenkins -> Configure System -> Global properties -> Environment variables 

See " Setting Environment Variables "

Setting the environment variable in Jenkins Pipeline can be done using the withEnv step, which allows you to override the specified environment variables for this Pipeline Script block, for example:

Jenkinsfile (Pipeline Script)

 node { /* .. snip .. */ withEnv(["NAME=value"]) { ... your job } } 
+37
source

When you reference env in the Groovy area, simply use env.VARIABLE_NAME, for example, to transfer BUILD_NUMBER of the outbound job to the running job:

 stage ('Starting job') { build job: 'TriggerTest', parameters: [ [$class: 'StringParameterValue', name: 'upstream_build_number', value: env.BUILD_NUMBER] ] } 
+2
source

Script pipeline To read an environment variable whose name you know, use env.NAME

To read an environment variable whose name is not known until runtime, use env.getProperty(name) .

For example, the value from the YAML configuration file represents the name of an environment variable:

config.yaml (in the workspace)

 myconfig: key: JOB_DISPLAY_URL 

Jenkinsfile

 node { println("Running job ${env.JOB_NAME}") def config = readYaml(file:'config.yaml') def value = env.getProperty(config.myconfig.key) println("Value of property ${config.myconfig.key} is ${value}") } 
+2
source

Env.VAR, env ['VAR'], env.getProperty ('VAR') are suitable for obtaining values.
For setting values, the only safe way at the moment is withEnv. If you try to assign env.VAR values, in some cases this may not work, for example, for parallel pipelines (as in JENKINS-59871 ).

0
source

Another syntax is $ ENV: xxxx

 node { echo "Running $ENV.BUILD_ID on $ENV.JENKINS_URL" } 

It worked for me

-3
source

Source: https://habr.com/ru/post/1261543/


All Articles