Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jenkins Global environment variables in Jenkinsfile

Tags:

How do I invoke Global environment variables in Jenkinsfile?
For example, if I have a variable -

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

How do I use it in the groovy script?

I tried ${credentialsId}, but it didn't work. It will just give error:

java.lang.NoSuchMethodError: No such DSL method '$' found among steps [ArtifactoryGradleBuild, ........ 
like image 783
ezlee Avatar asked Dec 20 '16 04:12

ezlee


People also ask

How do I add a global variable in Jenkins?

We can set global properties by navigating to “Manage Jenkins -> Configure System -> Global properties option”.

How do I view environment variables in Jenkinsfile?

Accessing Environment Variables We can start using env variables from the groovy interpreter site to pass a groovy string in an echo step, and I want to display the build number. So, in this case, we can use the groovy variable inside the groovy string and if you want to display BUILD_NUMBER.

How do you declare a variable in Jenkinsfile?

Environment variables can be defined using NAME = VALUE syntax. To access the variable value you can use these three methods $env.NAME , $NAME or ${NAME} There are no differences between these methods. Here is a complete pipeline sample with environment variables example.


2 Answers

In a Jenkinsfile, you have the "Working with the Environment" which mentions:

The full list of environment variables accessible from within Jenkins Pipeline is documented at localhost:8080/pipeline-syntax/globals#env,

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

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

See also "Managing the Environment".

How can I pass the Global variables to the Jenkinsfile?
When I say Global variables - I mean in

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

See "Setting environment variables"

Setting an environment variable within a Jenkins Pipeline can be done with the withEnv step, which allows overriding specified environment variables for a given block of Pipeline Script, for example:

Jenkinsfile (Pipeline Script)

node {     /* .. snip .. */     withEnv(["NAME=value"]) {         ... your job     } } 
like image 130
VonC Avatar answered Oct 18 '22 11:10

VonC


When referring to env in Groovy scope, simply use env.VARIABLE_NAME, for example to pass on BUILD_NUMBER of upstream job to a triggered job:

stage ('Starting job') {     build job: 'TriggerTest', parameters: [         [$class: 'StringParameterValue', name: 'upstream_build_number', value: env.BUILD_NUMBER]     ] } 
like image 22
Gudlaugur Egilsson Avatar answered Oct 18 '22 11:10

Gudlaugur Egilsson