Use withCredentials([usernamePassword( ... ) ]) in Jenkins Pipeline Library

Viewed 3968

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?

2 Answers

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);

Myabe not the best method, but you can use the credential in the pipeline and pass what you extract from it as a parameter to the class:

jenkinsfile:

import com.mydomain.gcp
Gcp gcp = new Gcp()

Pipeline{
environment {
 gcpCredentialId = 'YOUR-CREDENTIAL-ID'
}
        stages {
            stage('Authenticate') {
                steps {
                    script {
                        withCredentials([file(credentialsId: env.gcpCredentialId, variable: 'gcpAuthFile')]) {
                            gcp.authenticate("${gcpAuthFile}")
                        }
                    }
                }
            }
  }
}

then in the src\com\mydomain\Gcp.groovy file:

package com.mydomain.gcp
def authenticate(final String keyFile) {
  sh "gcloud auth activate-service-account --key-file=${keyFile}"
}
return this
Related