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, ........
We can set global properties by navigating to “Manage Jenkins -> Configure System -> Global properties option”.
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.
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.
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 } }
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] ] }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With