Jenkins Shared Pipeline Library: Can I declare static variables in a vars file?

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

Examples

The reference to global variables is "implicit" (does not 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 causes an error:

groovy.lang.MissingPropertyException: no such property: result for class: groovy.lang.Binding at groovy.lang.Binding.getVariable (Binding.java:63) in 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) ....

The reference to global variables is "explicit" (works)

 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 the variables are either initialized differently or simply cannot be used with the vars/ directory in the same way as a function. Is this feature part of Groovy? Or a limitation of the Jenkins Global Pipeline Library?

+6
source share
1 answer

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

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

Source: https://habr.com/ru/post/1011671/


All Articles