詹金斯:更改顶层环境变量

时间:2018-10-17 12:34:47

标签: jenkins jenkins-plugins jenkins-pipeline

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

1 个答案:

答案 0 :(得分:0)

我刚刚测试了下面的代码,它起作用了。在Docker中运行它不会产生任何影响。顶层“无代理”也不应该有任何影响,如果有的话,只需在顶层根据资源定义一个很小的代理即可。

# 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

因此变量值在各个阶段之间都存在,您可以在任何阶段进行更改。