I have a Jenkins shared lib in a repo, usual folder structure:
vars
utils.groovy
In utils.groovy I have some functions:
void funcA() {}
void funcB() {}
Now I want to define a constant that all functions in that module can use, but when I try this:
String common='hi'
void funcA() {println "A ${common}"}
void funcB() {println "B ${common}"}
I get an exception that common is not a symbol that exists:
groovy.lang.MissingPropertyException: No such property: common for class: utils
For now I'm getting around the issue by doing this hack:
String _getCommon() {
return 'hi'
}
void funcA() {String common=_getCommon(); println "A ${common}"}
void funcB() {String common=_getCommon(); println "B ${common}"}
Module level variables can be defined via the @Field:
import groovy.transform.Field
@Field var =...
void func() {println var}
Other modules in the same library can reference it too, the usual way. Ex assuming the above was defined in utils.groovy the other.groovy could have:
void func() {println utils.var}
See http://docs.groovy-lang.org/latest/html/gapi/groovy/transform/Field.html.
Looks like the CPS class loader does not support simple properties. However turns out that you can use something like:
class InnerClass {
static String myProperty = 'Hi'
}
String setCommon(String value) {
InnerClass.myProperty = value
}
String getCommon() {
return InnerClass.myProperty
}
void funcA() {println "A ${common}"}
void funcB() {println "B ${common}"}
Having this you may also access the property from within your Jenkinsfile like:
@Library('cpsLibFoo') _
utils.funcA()
utils.common = 'baz'
utils.funcB()
Output will be:
[Pipeline] echo
A Hi
[Pipeline] echo
B baz
[Pipeline] End of Pipeline
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