Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jenkinsfile: How to call a groovy function with named arguments

I have a simple Declarative Pipeline with function inside. How to correctly use named arguments for a function?

def getInputParams(param1='a', param2='b') {
    echo "param1 is ${param1}, param2 is ${param2}"
}

pipeline {
...
...
    stages {
        stage('Test) {
            steps {
                getInputParams(param1='x', param2='y')
            }
        }
    }
}

I cannot understand why named params become null in function?

[Pipeline] echo
param1 is null, param2 is null
...

Well, I'm able to call function like getInputParams('x', 'y'), but it's not human readable (arguments amount may increase in future)

like image 909
approximatenumber Avatar asked Dec 02 '19 12:12

approximatenumber


People also ask

How do I pass parameters in Groovy script Jenkins?

In the Name field add any name for your parameters and select the Groovy script in the Script radio buttons. Add a suitable description for your parameter. Next is Choice Type dropdown which has 4 choices available. Single Select : It will render a dropdown list from which a user can select only one value.

Does Groovy have named parameters?

Groovy collects all named parameters and puts them in a Map. The Map is passed on to the method as the first argument. The method needs to know how to get the information from the Map and process it.

How do you call a function in Groovy?

In Groovy, we can add a method named call to a class and then invoke the method without using the name call . We would simply just type the parentheses and optional arguments on an object instance. Groovy calls this the call operator: () .


1 Answers

Groovy is executed inside the Jenkinsfile so you have to follow its syntax for named arguments.

foo(name: 'Michael', age: 24)
def foo(Map args) { "${args.name}: ${args.age}" }

Quote from Groovy's named arguments:

Like constructors, normal methods can also be called with named arguments. They need to receive the parameters as a map. In the method body, the values can be accessed as in normal maps (map.key).

def getInputParams(Map map) {
    echo "param1 is ${map.param1}, param2 is ${map.param2}"
}

pipeline {
...
    stages {
        stage('Test') {
            steps {
                getInputParams(param1: 'x', param2: 'y')
            }
        }
    }
}
like image 149
Michael Kemmerzell Avatar answered Nov 15 '22 09:11

Michael Kemmerzell