approximatenumber
approximatenumber

Reputation: 507

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)

Upvotes: 8

Views: 17598

Answers (2)

Michael Kemmerzell
Michael Kemmerzell

Reputation: 5276

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

Upvotes: 13

Rahul Desai
Rahul Desai

Reputation: 319

If you are using groovy, use this.

def getInputParams(def param1, def param2) {
    println("param1 is "+ param1 + ", param2 is " + param2)
}

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

Upvotes: -5

Related Questions