Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jenkins Pipelines: How to use withCredentials() from a shared-variable script

I'd like to use a withCredentials() block in a shared-variable ("vars/") script rather than directly in the Jenkins pipeline because this is a lower-level semantic of a particular library, and also may or may not be required depending on the situation. However, withCredentials (or, at least, that signature of it) doesn't appear to be in scope.

script:

def credentials = [
    [$class: 'UsernamePasswordMultiBinding', credentialsId: '6a55c310-aaf9-4822-bf41-5500cd82af4e', passwordVariable: 'GERRIT_PASSWORD', usernameVariable: 'GERRIT_USERNAME'],
    [$class: 'StringBinding', credentialsId: 'SVC_SWREGISTRY_PASSWORD', variable: 'SVC_SWREGISTRY_PASSWORD']
]

withCredentials(credentials) {
// ...
}

Console:

hudson.remoting.ProxyException: groovy.lang.MissingMethodException: No signature of method: BuildagentInstallAndRun.withCredentials() is applicable for argument types: (java.util.ArrayList, org.jenkinsci.plugins.workflow.cps.CpsClosure2) values: [[[$class:UsernamePasswordMultiBinding, credentialsId:6a55c310-aaf9-4822-bf41-5500cd82af4e, ...], ...], ...]

Has anyone had any success with this?

like image 469
Dustin Oprea Avatar asked Jul 13 '18 16:07

Dustin Oprea


1 Answers

I'm using a shared library rather than a shared variable, but I guess it is a similar situation. I'm not using the $class parameter, but i'm calling directly one of the functions suggested by the pipeline snippet generator. You can have a list here. In the example below, I use the usernameColonPassword binding. In the pipeline, I instantiate the class utilities and I pass this to the constructor. Then, in the library, I use the step object to access the pipeline steps (such as withCredentials or usernameColonPassword).

class Utilities implements Serializable {
    def steps
    Utilities(steps) {
        this.steps = steps
    }
    def doArchiveToNexus(String credentials, String artifact, String artifact_registry_path){
        try {
            this.steps.withCredentials([steps.usernameColonPassword(credentialsId: credentials, variable: 'JENKINS_USER')]) {
                this.steps.sh "curl --user " + '${JENKINS_USER}' + " --upload-file ${artifact} ${artifact_registry_path}"
            }
        } catch (error){
            this.steps.echo error.getMessage()
            throw error
        }
    }
}
like image 169
Fabio Avatar answered Oct 13 '22 22:10

Fabio