10

My jenkins file looks like below:

import groovy.json.*
def manifestFile = "C:\\manifest.yml"

node {
  stage('Build') { 

  }
  stage('Deploy') { 
    checkDeployStatus()
  } 
}

def boolean checkDeployStatus() {
  echo "${manifestFile}"
  return true
}

The exception that i am getting is below:

groovy.lang.MissingPropertyException: No such property: manifestFile for class: groovy.lang.Binding
    at groovy.lang.Binding.getVariable(Binding.java:63)

How do i access variables outside the node?

mkobit
  • 43,979
  • 12
  • 156
  • 150
bigskull
  • 739
  • 2
  • 13
  • 23
  • For whom lands here, check the answer here: https://stackoverflow.com/questions/50571316/strange-variable-scoping-behavior-in-jenkinsfile – artegen Aug 13 '21 at 19:03

2 Answers2

13

Groovy has a different kind of scoping at the script level. I can't ever keep it all sorted in my head. Without trying explain all the reasons for it (and probably not doing it justice), I can tell you that (as you have seen), the manifestFile variable is not in scope in that function. Just don't declare the manifestFile (i.e. don't put def in front of it). That will make it a "global" (not really, but for your purposes here) variable, then it should be accessible in the method call.

Rob Hales
  • 5,123
  • 1
  • 21
  • 33
7

try this

import groovy.json.*
manifestFile = "C:\\manifest.yml"

node {
  stage('Build') { 

  }
  stage('Deploy') { 
    checkDeployStatus()
  } 
}

def boolean checkDeployStatus() {
  echo "${manifestFile}"
  return true
}
dazito
  • 7,740
  • 15
  • 75
  • 117
Nirmal
  • 181
  • 3
  • Be aware there are some potential issues with this approach. It's recommend to annotate the variable with `@Field` if you want to change the scope. See this [answer](https://stackoverflow.com/a/50573082/6405287) – Skillz May 12 '23 at 18:17