Issue
I'm trying to move some functions from a Jenkins Pipeline to a shared jenkins library. But I get errors when using the Credentials Binding Plugin (withCredentials)
For example I have this block of code:
withCredentials([usernamePassword(credentialsId: 'foobar', usernameVariable: 'fooUser', passwordVariable: 'fooPassword')]) {
// do something with credentials
}
When I move this block to a static library function I get the following error:
hudson.remoting.ProxyException:
groovy.lang.MissingMethodException:
No signature of method: static mylib.MyClass.usernamePassword() is applicable for argument types:
(java.util.LinkedHashMap) values: [[credentialsId:foobar, usernameVariable:fooUser, ...]]
Library Code:
package mylib;
class MyClass {
def static String doSomething() {
withCredentials([usernamePassword(credentialsId: 'foobar', usernameVariable: 'fooUser', passwordVariable: 'fooPassword')]) {
// some code
}
}
}
Usage in Jenkins Pipeline:
@Library('my-pipeline-library')
import mypackage.MyClass
...
MyClass.doSomething();
How can I use withCredentials/usernamePassword in my Jenkins Library? Do I need to qualify the functions with some package? Do I need extra imports? Is there any documentation about this?
Solution
I found a possible solution, not sure if i really like it:
I can pass the current script (this) from the pipeline script to the library. Then I can use this script variable to use functions in my pipeline library.
Looks like this:
Library Code:
package mylib;
class MyClass {
def static String doSomething(script) {
script.withCredentials([script.usernamePassword(credentialsId: 'foobar', usernameVariable: 'fooUser', passwordVariable: 'fooPassword')]) {
// some code
}
}
}
Usage in Jenkins Pipeline:
@Library('my-pipeline-library')
import mypackage.MyClass
...
MyClass.doSomething(this);
Answered By - TomStroemer