gpt4 book ai didi

jenkins - 如何在脚本化的 Jenkins 管道中定义全局变量

转载 作者:行者123 更新时间:2023-12-05 01:30:51 27 4
gpt4 key购买 nike

我想在 Jenkins 脚本化管道中定义一个全局变量,它可以在管道中的任何位置访问。即任何阶段和任何方法。如果我在管道顶部定义 var,它在 node 声明和 stage 声明中起作用,但在被调用的方法中不起作用。我不想使用 env.XXX 和 withEnv([]),因为我可能不得不从不同的地方调用这些方法,这意味着有时使用 env,而不是其他地方。

这是我用于脚本管道的简单 JenkinsFile:

def jenkinsNode = 'linux'
def DEBUG = 1

node(jenkinsNode){
echo ">> node($jenkinsNode)"
echo "DEBUG = $DEBUG"

if (DEBUG) {
echo "DEBUG is On"}
else {
echo "DEBUG is Off"
}

stage('test-this') {
if (DEBUG) {
echo "DEBUG is On"}
else {
echo "DEBUG is Off"
}

testMethod()
}
echo "<< node($jenkinsNode)"
}

def testMethod() {
echo ">> testMethod()"

if (DEBUG) {
echo "DEBUG is On"}
else {
echo "DEBUG is Off"
}

echo "<< testMethod()"
}

当我运行它时,我得到:

Running on rh6-a01 in /jenkins_home/jenkins-rh6-a01/a98289de/workspace/test/test/test-global
[Pipeline] {
[Pipeline] echo
>> node(linux)
[Pipeline] echo
DEBUG = 1
[Pipeline] echo
DEBUG is On
[Pipeline] stage
[Pipeline] { (test-this)
[Pipeline] echo
DEBUG is Off
[Pipeline] echo
>> testMethod()
[Pipeline] }
[Pipeline] // stage
[Pipeline] }
[Pipeline] // node
[Pipeline] End of Pipeline
hudson.remoting.ProxyException: groovy.lang.MissingPropertyException: No such property: DEBUG for class: WorkflowScript
[...snip...]

我如何编写允许任何方法访问 DEBUG 变量的 Jenkinsfile?

最佳答案

从顶部的声明中删除 def 可以解决这个问题。

def jenkinsNode = 'linux'
DEBUG = 1

node(jenkinsNode){
echo ">> node($jenkinsNode)"
echo "DEBUG = $DEBUG"

if (DEBUG) {
.....

给出输出

>> node(linux)
[Pipeline] echo
DEBUG = 1
[Pipeline] echo
DEBUG is On
[Pipeline] stage
[Pipeline] { (test-this)
[Pipeline] echo
DEBUG is On
[Pipeline] echo
>> testMethod()
[Pipeline] echo
DEBUG is On
[Pipeline] echo
<< testMethod()
[Pipeline] }
[Pipeline] // stage
[Pipeline] echo
<< node(docker)
[Pipeline] }
[Pipeline] // node
[Pipeline] End of Pipeline
Finished: SUCCESS

这是因为使用 def 将变量绑定(bind)到当前作用域(方法内容不在其中)。不使用 def 不会绑定(bind)允许它在脚本中的任何地方使用的范围。

请注意,Groovy 不会阻止您在其他地方使用带有 def 的变量,这可能会导致意想不到的结果,例如在方法中添加 def DEBUG = 0

def testMethod() {
echo ">> testMethod()"
def DEBUG = 0

if (DEBUG) {
echo "DEBUG is On"}
else {
echo "DEBUG is Off"
}

仍然可以正常运行,但会在该方法中关闭 DEBUG。

关于jenkins - 如何在脚本化的 Jenkins 管道中定义全局变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66694960/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com