如何使用 Jenkinsfile 在 groovy 函数中使用环境变量 [英] How to use environment variables in a groovy function using a Jenkinsfile
问题描述
我正在尝试使用在 Jenkinsfile 中的任何节点之外定义的环境变量.我可以在任何节点的任何管道步骤中将它们纳入范围,但不能在函数内部.我现在能想到的唯一解决方案是将它们作为参数传递.但我想直接在函数内部引用环境变量,这样我就不必传入这么多参数.这是我的代码.如何让函数输出正确的 BRANCH_TEST
值?
I'm trying to use environment variables defined outside any node in a Jenkinsfile. I can bring them in scope on any pipeline step in any node but not inside of a function. The only solution I can think of for now is to pass them in as parameters. But I would like to reference the env variables directly inside the function so I don't have to pass so many parameters in. Here is my code. How can I get the function to output the correct value of BRANCH_TEST
?
def BRANCH_TEST = "master"
node {
deploy()
}
def deploy(){
echo BRANCH_TEST
}
Jenkins 控制台输出:
Jenkins console output:
[Pipeline]
[Pipeline] echo
null
[Pipeline] }
[Pipeline] // node
[Pipeline] End of Pipeline
Finished: SUCCESS
推荐答案
解决方案是
使用
@Field
注解
从声明中删除 def.有关使用 def 的说明,请参阅 Ted 的回答.
Remove def from declaration. See Ted's answer for an explanation on using def.
解决方案 1(使用 @Field
)
Solution 1 (using @Field
)
import groovy.transform.Field
@Field def BRANCH_TEST = "master"
node {
deploy()
}
def deploy(){
echo BRANCH_TEST
}
解决方案 2(删除 def)
Solution 2 (removing def)
BRANCH_TEST = "master"
node {
deploy()
}
def deploy(){
echo BRANCH_TEST
}
说明是这里,
也在这个 SO 问题中回答:如何创建和访问全局变量时髦的?
also answered in this SO question: How do I create and access the global variables in Groovy?
这篇关于如何使用 Jenkinsfile 在 groovy 函数中使用环境变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!