vartec vartec - 1 year ago 39
Groovy Question

Why do I need keyword `this` while using `env` or `param` in DSL closure in Jenkinsfile

I have code based on "structured DSL" concept.

// vars/buildStuff.groovy
def call(body) {

def config = [:]
body.resolveStrategy = Closure.DELEGATE_FIRST
body.delegate = config
body()

node {
assert env
assert params
doStuff()
}
}


In this code I can access
env
and
params
directly, as expected.

However in the top level
Jenkinsfile
:

buildStuff {
someParam=params.SOME_PARAM
buildId=env.BUILD_ID
}


Causes
java.lang.NullPointerException: Cannot get property 'SOME_PARAM' on null object
. I have to work around that by writing this as:

buildStuff {
someParam=this.params.SOME_PARAM
buildId=this.env.BUILD_ID
}


Why is that the case? According to all examples in Pipelines documentation I should be able to access
env
and
params
directly.
What am I doing wrong?

Answer Source

It's an issue with the resolveStrategy.

def config = [:]
body.resolveStrategy = Closure.DELEGATE_FIRST
body.delegate = config

The config you provide resolves any property to its value or null, thus the owner is not queried for it. In you example the owner is just this. That's why it works.

Depending on what you're actually trying to achieve, OWNER_FIRST might be a better strategy. If you cannot change this, better use a data structure without defaults for properties.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download