jenkinsgroovyjenkins-pipelinejenkins-groovypositional-parameter

How To Set Positional Arguments in Jenkins Groovy


Does Groovy support positional arguments?

I have a function defined in a Jenkins shared library name.groovy

def call(name, age) {
sh """
echo "My name is: ${name}"
echo "My age is: ${age}"
"""
}

And when I call it from the pipeline

stage ('Shared Library') {
   steps {
      name("Foo", "21")
    }   
 }

It works perfectly and I get

My name is Foo

My age is 21

However, I would like to set the arguments positionally so that it prints correctly regardless of how they're placed.

But when I do

stage ('Shared Library') {
   steps {
      name(age: "21", name: "Foo")
    }   
 }

I get

My name is null

My age is null

Is there a way to set this correctly?


Solution

  • What you are asking here is how to use a Map type as the input argument for your custom step method global variable. age: "21", name: "Foo" would be a Map in this situation. You can refactor the global variable method for your custom step like this:

    def call(Map args) {
      sh """
        echo "My name is: ${args.name}"
        echo "My age is: ${args.age}"
      """
    }
    

    and then you could invoke in your pipeline steps:

    stage ('Shared Library') {
      steps {
        name(age: '21', name: 'Foo')
      }   
    }
    

    with the expected results.

    We could also improve the method with some intrinsic Groovy methods and argument checks with the null coalescing operator:

    def call(Map args) {
      // provide defaults for arguments
      args.name = args.name ?: 'no name'
      args.age = args.age ?: 'unknown age'
      // output name and age to stdout
      print "My name is: ${args.name}"
      print "My age is: ${args.age}"
    }