简体   繁体   English

如何在 Jenkins 脚本管道中设置环境变量?

[英]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:根据Jenkins 文档,这是为声明性管道设置全局环境变量的方式:

pipeline {
    agent {
        label 'my-label'
    }
    environment {
        value = 'World'
    }
    stages {
        stage("Test") {
            steps {
                sh 'echo Hello, ${value}'
            }
        }
    }
}

The output is "Hello, World" as expected.正如预期的那样,输出是“Hello, World”。

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.这并不像预期的那样。

Click Toggle Scripted Pipeline at this link单击此链接中的切换脚本化管道

Jenkinsfile (Scripted Pipeline) Jenkinsfile(脚本化流水线)

  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.在脚本化管道(以及声明性管道的脚本部分)中,您可以通过“env”全局对象直接设置环境变量。

node {
    env.MY_VAR = 'my-value1'
}

You can also set variables dynamically like this:您还可以像这样动态设置变量:

node {
    def envVarName = 'MY_VAR' 
    env.setProperty(envVarName, 'my-value2')
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM