在 Groovy 中访问闭包外的变量

Accessing variable outside of a closure in Groovy

有没有办法,我可以访问闭包外的变量。这里的闭包是Jenkinsfile中的一个stage。因此,代码段如下所示:

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
   }

  }

使用此代码,我无法访问在第一个 stage/closure 中创建的 list

我如何设置才能让下一个 stage/closure 可以访问这个新创建的 list

@tim_yates.. 采纳你的建议。这行得通。最后很容易:)

node('pool') {
  try {
    def list = [] //define the list outside of the closure

    stage('init') {
      //some code to create/push elements in the list
    }
    stage('deploy') {
      //use the list create in the above stage/closure
    }

  } catch (err) {
    //some mail step
  }

}

我知道已经晚了,但值得一提的是,当您定义类型或 def(用于动态解析)时,您正在创建一个 local scope 变量,它将仅在封闭内可用。

如果省略声明,变量将对整个脚本可用:

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"
    }
}

Returns :

The value of list is 2
The value of list is 3
Final value of list is 3