11
votes

Does Jenkins Shared Pipeline Library supports static variables in vars/*. groovy files?

Examples

Referencing global variables "implicitly" (doesn't work)

file: vars/foo.groovy
---
def functionFoo() {return "foo"}



file: vars/bar.groovy
---
def result = functionFoo()
def functionBar() {println result}


file:Jenkinsfile
---
@Library('MyLib') _
bar.functionBar()

This throws error:

groovy.lang.MissingPropertyException: No such property: result for class: groovy.lang.Binding at groovy.lang.Binding.getVariable(Binding.java:63) at org.jenkinsci.plugins.scriptsecurity.sandbox.groovy.SandboxInterceptor.onGetProperty(SandboxInterceptor.java:224) at org.kohsuke.groovy.sandbox.impl.Checker$4.call(Checker.java:241) at org.kohsuke.groovy.sandbox.impl.Checker.checkedGetProperty(Checker.java:238) at com.cloudbees.groovy.cps.sandbox.SandboxInvoker.getProperty(SandboxInvoker.java:24) at com.cloudbees.groovy.cps.impl.PropertyAccessBlock.rawGet(PropertyAccessBlock.java:20) ....

Referencing global variables "explicitly" (does work)

file: vars/foo.groovy
---
def functionFoo() {return "foo"}



file: vars/bar.groovy
---
def functionBar() {
    def result = functionFoo()
    println result
}


file:Jenkinsfile
---
@Library('MyLib') _
bar.functionBar()

Summary

I assume that variables are either initialized in different way or simply cannot be used withing vars/ directory the same way function can. Is this feature part of Groovy language? Or a limitation of Jenkins' Global Pipeline Library?

1
Have you tried this? - izzekil

1 Answers

8
votes

To define a variable inside the groovy vars, rather than a function, use groovy.transform.Field:

@groovy.transform.Field result = functionFoo()
def functionBar() {println this.result}