Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to access variables outside stages in Jenkins file Groovy function?

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?

like image 208
bigskull Avatar asked Oct 30 '17 02:10

bigskull


People also ask

How to resolve Groovy variables in Jenkins pipeline?

The easiest way is to let the dynamic Groovy object resolution implemented by Jenkins resolve your variable. To instead lookup the foo from the script object (which I am presuming is the this or script in your Jenkins pipeline by new Foo (this, config) ):

How to print Jenkins Pipeline environment variables in logs?

The steps to do the same are : Create a new pipeline in Jenkins, named ‘ envvars ’. In the Pipeline Script, type the following groovy script. The windows batch command used here is “ set ”. This command lists all the Jenkins pipeline environment variables in logs. sh ‘printenv’ .

What are the different types of variables in Jenkins?

Commonly used variable types in Jenkins include env (environment variables), currentBuild, params (parameters), and docker (access to Docker functions). Jenkins saves all current environment variables in list form.

How to view environment variables in Jenkins using shell command?

For instance, when logging in on your system using the default port 8080: Another method is to create a Jenkins job that executes a shell command to view environment variables. The console output of this job is a modified version of the environment variables list.


1 Answers

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.

like image 80
Rob Hales Avatar answered Oct 13 '22 00:10

Rob Hales