Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set environment variables in a Jenkins Scripted Pipeline?

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.

like image 813
roadSurfer Avatar asked Mar 12 '19 13:03

roadSurfer


People also ask

How do I set environment variable in Jenkins pipeline stage?

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.

How do you declare a variable in Jenkins pipeline script?

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.


2 Answers

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}'
           }
      }
  }
like image 96
bot Avatar answered Oct 22 '22 23:10

bot


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')
}
like image 21
sola Avatar answered Oct 22 '22 23:10

sola