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)
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.
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.
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: () .
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')
}
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With