Following the link here we have our own DSL extension which is defined like this in a file vars/buildFlow.groovy:
Map<String, Object> mapFromClosure(Closure body) {
Map<String, Object> config = [:]
body.resolveStrategy = Closure.DELEGATE_FIRST
body.delegate = config
body()
// other things
}
In my Jenkinsfile, I can use this as such:
buildFlow {
// different args
}
I would like to be able to dynamically populate the args to buildFlow but am unsure how to work with Groovy and closures. I have a Map of everything I want based on my conditions, but I can't pass the Map to buildFlow like this. Is there a way to convert the Map args to the closure constructor?
Map flowArgs = [
argA: 1,
argB: 2
]
buildFlow {
flowArgs
}
I've seen solutions which talk about using ConfigObject but that is restricted:
Scripts not permitted to use new groovy.util.ConfigObject
To dynamically populate the arguments for
buildFlowusing aMap, you might consider converting theMapto a closure in Groovy.That can be done by iterating through the
Mapand applying each key-value pair as properties to a closure.First, modify the
mapFromClosuremethod invars/buildFlow.groovyto handle bothClosureandMaptypes:Then, create a utility method to convert a
Mapto aClosure(as in "Groovy converting between Map and Closure"):Use this utility method in your
Jenkinsfileto convert yourMapto a closure before passing it tobuildFlow:Result:
That would provide the flexibility to handle both closures and maps in your DSL, allowing dynamic argument passing to
buildFlow.The
mapToClosurefunction is used within the Jenkins pipeline to convert theMapof arguments into aClosurebefore passing it tobuildFlow. That makes sure the pipeline script stays within the boundaries of what is allowed by Jenkins' script security.