在 Jenkins 管道库中使用 withCredentials([usernamePassword( ... ) ])

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

我正在尝试将一些函数从 Jenkins 管道移动到共享的 jenkins 库。但是在使用凭据绑定插件 (withCredentials)

时出现错误

例如我有这段代码:

withCredentials([usernamePassword(credentialsId: 'foobar', usernameVariable: 'fooUser', passwordVariable: 'fooPassword')]) {
    // do something with credentials
}

当我将此块移动到静态库函数时,出现以下错误:

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, ...]]

图书馆代码:

package mylib;

class MyClass {

    def static String doSomething() {
        withCredentials([usernamePassword(credentialsId: 'foobar', usernameVariable: 'fooUser', passwordVariable: 'fooPassword')]) {
            // some code
        }
    }
}

Jenkins 管道中的用法:

@Library('my-pipeline-library')
import mypackage.MyClass
...
MyClass.doSomething();

如何在我的 Jenkins 库中使用 withCredentials/usernamePassword?我需要用一些包来限定功能吗?我需要额外的进口吗?有没有关于这个的文档?

我找到了一个可能的解决方案,不确定我是否真的喜欢它:

我可以将当​​前脚本 (this) 从管道脚本传递到库中。然后我可以使用这个脚本变量来使用我的管道库中的函数。

看起来像这样:

图书馆代码:

package mylib;

class MyClass {

    def static String doSomething(script) {
        script.withCredentials([script.usernamePassword(credentialsId: 'foobar', usernameVariable: 'fooUser', passwordVariable: 'fooPassword')]) {
            // some code
        }
    }
}

Jenkins 管道中的用法:

@Library('my-pipeline-library')
import mypackage.MyClass
...
MyClass.doSomething(this);

Myabe 不是最好的方法,但您可以在管道中使用凭据并将从中提取的内容作为参数传递给 class:

詹金斯文件:

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

然后在 src\com\mydomain\Gcp.groovy 文件中:

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