我正在尝试将一些函数从 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?我需要用一些包来限定这些功能吗?我需要额外的进口吗?有关于此的任何文档吗?
答案 0 :(得分:0)
我找到了一个可能的解决方案,不确定我是否真的喜欢它:
我可以将当前脚本(this)从管道脚本传递到库。然后我可以使用这个脚本变量来使用我的管道库中的函数。
看起来像这样:
库代码:
updateTable()
在 Jenkins 流水线中的使用:
package mylib;
class MyClass {
def static String doSomething(script) {
script.withCredentials([script.usernamePassword(credentialsId: 'foobar', usernameVariable: 'fooUser', passwordVariable: 'fooPassword')]) {
// some code
}
}
}
答案 1 :(得分:0)
Myabe 不是最好的方法,但您可以使用管道中的凭据并将从中提取的内容作为参数传递给类:
詹金斯文件:
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