Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

library variable in jenkins shared library

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}"}
like image 510
Oliver Avatar asked Oct 29 '25 12:10

Oliver


2 Answers

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.

like image 69
Oliver Avatar answered Nov 01 '25 13:11

Oliver


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
like image 33
Joerg S Avatar answered Nov 01 '25 13:11

Joerg S



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!