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?
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
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