Search code examples
jenkinsgroovyjenkins-pipeline

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)


Solution

  • 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')
                }
            }
        }
    }