Jenkins Pipelines:如何从共享变量脚本中使用withCredentials() [英] Jenkins Pipelines: How to use withCredentials() from a shared-variable script
问题描述
我想在共享变量("vars/")脚本中使用withCredentials()
块,而不是直接在Jenkins管道中使用,因为这是特定库的低级语义,并且可能视情况而定,可能不需要.但是,withCredentials
(或至少它的签名)似乎不在范围内.
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.
脚本:
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) {
// ...
}
控制台:
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, ...], ...], ...]
有人能成功吗?
推荐答案
我使用的是共享库,而不是共享变量,但我想这是类似的情况.
我没有使用$class
参数,而是直接调用了管道摘要生成器建议的功能之一.您可以在此处获得列表.在下面的示例中,我使用usernameColonPassword
绑定.
在管道中,我实例化了类实用程序,并将this
传递给了构造函数.然后,在库中,我使用step
对象访问管道步骤(例如withCredentials
或usernameColonPassword
).
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
}
}
}
这篇关于Jenkins Pipelines:如何从共享变量脚本中使用withCredentials()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!