Lazy GString in the current context in Jenkins

Viewed 128

I have a Jenkins pipeline script. I need to do lazy evaluation on a GString. I understand that I can't use a closure inside a GString as I would normally do. However, if I create a closure that returns a GString (as suggested in the Jenkins documentation), it is evaluated in the context in which it was defined, not the current context.

I can't copy the code over from my corporate environment, so this is a made up example.

// At the start of the script
def deferredPom = {-> "${pom}"}

// somewhat later, inside a stage
def pom = readMavenPom
println "${pom}            // works, prints com.company:test:0.0.1-SNAPSHOT, or whatever
println deferredPom.call() // throws MissingPropertyException because pom is not defined

The problem here seems to be that the parent of deferredPom is an instance of WorkflowScript, whereas the parent at the time it is being evaluated is an instance of CpsClosure2. Clearly, pom only exists in the context of the current closure.

I would like to evaluate deferredPom in the current context, not the context in which it was defined.

I have toyed with using GroovyShell, but firstly I can't make that work as I don't seem to be able to pass the right context (I'll probably sort that out), but secondly and most importantly, I don't want to have to permit scripts to execute evaluate.

0 Answers
Related