Jenkins:更改顶级环境变量

Jenkins: change top level environment variable

我在定义了 agent none 的声明性管道的顶层设置了环境变量。 我如何使用 docker 代理在阶段内更改它的值? 我需要在代理之间保持更改后的值。

我刚刚测试了下面的代码并且它有效。 运行 它在 Docker 中应该不会有任何影响。顶层 "agent none" 也不应该有任何影响,如果有影响,只需在顶层定义一个非常小的资源明智的代理。

# Define the variable and set it to some value.
myVar = 12
# A function to use in the environment blocks below.
def getVar() {
    return myVar
}
pipeline {
    agent any
    environment {
        # Set the environment variable to the value of the Groovy variable.
        MY_VAR = getVar()
    }
    stages {
        stage("Test1") {
            steps {
                script {
                    # Change the value of the Groovy variable.
                    myVar = 13
                }
                # The environment variable won't change as long as we don't use an environment block to change it.
                sh "echo ${MY_VAR}"
            }
        }
        stage("Test2") {
            environment {
                # Updating the environment variable.
                MY_VAR = getVar()
            }
            steps {
                # And checking that it has been updated.
                sh "echo ${MY_VAR}"
            }
        }
    }
}

对我来说这会打印:

+ echo 12
12
[Pipeline] }
[Pipeline] // stage
[Pipeline] stage
[Pipeline] { (Test2)
[Pipeline] withEnv
[Pipeline] {
[Pipeline] sh
[Pipeline__all-branches__CI] Running shell script
+ echo 13
13

因此变量值在各个阶段之间保持不变,您可以在任何阶段更改它。