[英]How do I define a global variable in a scripted jenkins pipeline
我想在 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) {
.....
給output
>> 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
將變量綁定到當前 scope (方法內容不在其中)。 不使用def
不會綁定 scope 允許它在腳本中的任何地方使用。
請注意認為 Groovy 不會阻止您在其他地方使用帶有def
的變量,這可能會導致意外結果,例如在方法中添加def DEBUG = 0
def testMethod() {
echo ">> testMethod()"
def DEBUG = 0
if (DEBUG) {
echo "DEBUG is On"}
else {
echo "DEBUG is Off"
}
仍然可以正常運行,但會在該方法中關閉 DEBUG。
......
testMethod(DEBUG)
}
echo "<< node($jenkinsNode)"
}
def testMethod(DEBUG) {
echo ">> testMethod()"
if (DEBUG) {
echo "DEBUG is On"}
else {
echo "DEBUG is Off"
}
echo "<< testMethod()"
}
@Field
注釋將按照此答案https://stackoverflow.com/a/37425799/10697591中的說明工作import groovy.transform.Field
@Field def DEBUG = 1
def jenkinsNode = 'master'
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()"
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.