在Groovy中访问闭包外部的变量
有没有办法,我可以访问闭包外的变量。这里的闭包是在Groovy中访问闭包外部的变量,groovy,scope,jenkins-pipeline,Groovy,Scope,Jenkins Pipeline,有没有办法,我可以访问闭包外的变量。这里的闭包是Jenkinsfile中的阶段。因此,代码段如下所示: node('pool'){ try{ stage('init'){ def list = [] //some code to create the list } stage('deploy'){ //use the list create in the above stage/closure } } catch(err)
Jenkinsfile
中的阶段。因此,代码段如下所示:
node('pool'){
try{
stage('init'){
def list = []
//some code to create the list
}
stage('deploy'){
//use the list create in the above stage/closure
}
}
catch(err){
//some mail step
}
}
使用此代码,我无法访问在第一个阶段/结束
中创建的列表
如何设置使新创建的列表可供下一阶段/结束访问 @tim_yates。。同意你的建议。这很有效。最后很容易:)
我知道现在已经晚了,但值得一提的是,当您定义一个类型或def
(用于动态解析)时,您正在创建一个局部范围变量,该变量将仅在闭包内可用
如果省略声明,则整个脚本都可以使用该变量:
node('pool'){
try {
stage('Define') {
list = 2
println "The value of list is $list"
}
stage('Print') {
list += 1
echo "The value of list is $list"
}
1/0 // making an exception to check the value of list
}
catch(err){
echo "Final value of list is $list"
}
}
返回:
The value of list is 2
The value of list is 3
Final value of list is 3
在闭包之外创建它?@tim_yates我可以这样做,但我想把所有东西都打包在stages w.r.t.Jenkins文件中。如果我在jenkinsfile中使用了stage的闭包,它会抛出警告,对“stage”使用闭包是的,但是如果你把列表放在闭包中,你就不能从闭包外访问它。。。所以你的选择是有限的;-)
The value of list is 2
The value of list is 3
Final value of list is 3