Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to access global variables inside groovy class files?

I have the following directory structure

(root)
+- src                     # Groovy source files
|   +- org
|       +- foo
|           +- Bar.groovy  # for org.foo.Bar class
+- vars
|   +- foo.groovy          # for global 'foo' variable

And I have the following lines of code in the following files

  1. Bar.groovy

    package org.foo
    
    class Bar implements Serializable {
      def config
      def script
    
      Bar(script, config){
        this.script = script
        this.config = config
      }
    
      def accessGlobalVars(){
        this.script.echo "${foo.GlobalVar}" // throws an err
      }
    }
    
  2. foo.groovy

    import groovy.transform.Field
    @Field GlobalVar="Hello World!"
    

I'm able to access the variable in the Jenkinsfile inside the script block

echo "${foo.GlobalVar}"

Is it possible to access the same variable inside the class since the vars folder is at src folder level?

like image 597
k_vishwanath Avatar asked Mar 20 '18 10:03

k_vishwanath


1 Answers

The "${foo.GlobalVar}" in your example code is trying to resolve the foo against the Bar type. Since there is no foo reference it cannot be resolved and you will probably get something like a MissingPropertyException.

Jenkins Pipeline Groovy does some different compilation and binding using the Groovy compilation and runtime APIs. The global variables can also be resolved through the script object through its dynamic GroovyObject APIs (demonstrated in the source code here). The easiest way is to let the dynamic Groovy object resolution implemented by Jenkins resolve your variable.

Change your line from:

this.script.echo "${foo.GlobalVar}"

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)):

this.script.echo "${this.script.foo.GlobalVar}"
like image 65
mkobit Avatar answered Oct 25 '22 05:10

mkobit