29

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.

2 Answers 2

28

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}' } } } 
Sign up to request clarification or add additional context in comments.

1 Comment

Ah, thank you. I also discovered that " env.value='World' " also works.
22

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') } 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.