如何使用Jenkinsfile在Groovy函数中使用环境变量 [英] How to use environment variables in a groovy function using a Jenkinsfile
问题描述
我正在尝试使用在Jenkinsfile中的任何节点之外定义的环境变量.我可以将它们置于任何节点中任何管道步骤上的作用域中,但不能置于函数内部.我现在唯一想到的解决方案是将它们作为参数传递.但是我想直接在函数内部引用env变量,因此不必传入太多参数.这是我的代码.如何获得输出正确的 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
)
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问题中也回答了:如何在以下位置创建和访问全局变量是Groovy吗?
also answered in this SO question: How do I create and access the global variables in Groovy?
这篇关于如何使用Jenkinsfile在Groovy函数中使用环境变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!