Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I access global variables (currentBuild, env, ...) from within a Shared Library?

I'd like to access a global variable like currentBuild, env, etc. from within a shared Groovy library.

Example 1 (works):

// vars/customStep.groovy
def call() {
    echo env.myParameter
}

Example 2 (doesn't work):

// vars/customStep.groovy
class customStep implements Serializable {
    def call() {
        echo env.myParameter
    }
}

Example 3 (doesn't work):

// src/com/acme/Lib.groovy
package com.acme
class Lib {
    def someMethod() {
        echo env.myParameter
    }
}

I'd like to be able to access the variables in either case. How can I do this?

like image 443
nepa Avatar asked Oct 24 '25 04:10

nepa


1 Answers

If you use the env variable from inside a class definition, Groovy will try to access a class variable env, rather than a global variable. I think you need to create a constructor and pass the env variable into it. For example:

package com.acme
class Lib {
    def env
}

and in your pipeline use:

 def library = Lib(env: env)

I take groovy constructor syntax from here

like image 164
whitediver Avatar answered Oct 27 '25 03:10

whitediver



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!