OK999
OK999

Reputation: 1399

Accessing variable outside of a closure in Groovy

Is there a way, i can access a variable outside the closure. The closure here is a stage in the Jenkinsfile. So, the snippet looks like this:

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
   }

  }

With this code, i cannot access the list which was created in the first stage/closure.

How can i set to get this newly created list accessible to the next stage/closure?

Upvotes: 3

Views: 5283

Answers (2)

Bernardo Vale
Bernardo Vale

Reputation: 3544

I know it's late, but worths mentioning that when you define a type or def (for dynamic resolution) you're creating a local scope variable that will be available only inside the closure.

If you omit the declaration the variable will be available to the whole script:

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

Upvotes: 1

OK999
OK999

Reputation: 1399

@tim_yates.. with your suggestion. This works. It was easy at the end :)

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
  }

}

Upvotes: 2

Related Questions