According to the Jenkins docs, this is how one sets a Global Environment Variable for a Declarative Pipeline:
pipeline {
agent {
label 'my-label'
}
environment {
value = 'World'
}
stages {
stage("Test") {
steps {
sh 'echo Hello, ${value}'
}
}
}
}
The output is "Hello, World" as expected.
What is the correct way to do this in a Scripted Pipeline? The following does not error, but it does not work:
node('my-label') {
environment {
value = 'World'
}
stage("Test") {
sh 'echo Hello, ${value}'
}
}
The output is "Hello, ". That is not as expected.
Setting Stage Level Environment Variable It is by using the env variable directly in the script block. We can define, let us say, USER_GROUP and display it. You will see that the underlying shell also has access to this environment variable. You can also set an environment variable using withEnv block.
Jenkins pipeline environment variables: You can define your environment variables in both — global and per-stage — simultaneously. Globally defined variables can be used in all stages but stage defined variables can only be used within that stage. Environment variables can be defined using NAME = VALUE syntax.
Click Toggle Scripted Pipeline at this link
Jenkinsfile (Scripted Pipeline)
node {
withEnv(['DISABLE_AUTH=true',
'DB_ENGINE=sqlite']) {
stage('Build') {
sh 'printenv'
}
}
}
Your script should look something like the following:
node('my-label') {
withEnv(['value=World']) {
stage('Test') {
sh 'echo Hello, ${value}'
}
}
}
In Scripted Pipelines (and in script sections of Declarative Pipelines) you can set environment variables directly via the "env" global object.
node {
env.MY_VAR = 'my-value1'
}
You can also set variables dynamically like this:
node {
def envVarName = 'MY_VAR'
env.setProperty(envVarName, 'my-value2')
}
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