Lars Bilke
Lars Bilke

Reputation: 5229

How to pass a map to a Jenkins Pipeline global function?

I have a global function like this:

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

    body()

    echo config.name      // works
    echo config.configure // is null
}

Which is called like this:

myStep {
    name = 'linux-build'
    configure = [os: 'linux', dir: 'build']

    echo "myStep"
}

Normal variables (name) are working but the passed map (configure) does not. Maybe that is because of def config = [:]? How can I access the map inside the function?

Upvotes: 1

Views: 8254

Answers (1)

albciff
albciff

Reputation: 18507

The Map is really passed the problem is that echo don't know how to deal with Map in order to print in the console (seems that echo only prints string).

So you can try with the follow code instead:

echo config.configure.toString() // prints [os:linux, dir:build]

Or using GString:

echo "${config.configure}" // prints [os:linux, dir:build]

Or using println:

println config.configure // prints  {os=linux, dir=build}

So the thing is that Map is there so you can access config.configure.os or config.configure.dir without problems, try with the follow code in the jenkins-pipeline:

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

    body()

    echo config.name      // works
    echo config.configure.os // prints linux
    echo config.configure.dir // prints buid
    println config.configure // prints {os=linux, dir=build}
}

myStep {
    name = 'linux-build'
    configure = [os: 'linux', dir: 'build']
    echo "myStep"
}

It shows the follow result in the Output console:

[Pipeline] echo
myStep
[Pipeline] echo
linux-build
[Pipeline] echo
linux
[Pipeline] echo
build
[Pipeline] echo
{os=linux, dir=build}
[Pipeline] End of Pipeline
Finished: SUCCESS

Upvotes: 4

Related Questions