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
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
}
}
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?
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}"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With