jenkins - 如何在 Jenkins 共享变量中使用 Closure 创建包装 Jenkins withCredentials 的 withXCredentials?
问题描述
我想在我的管道脚本中使用这种语法的代码:
withXCredentials(id: 'some-cred-id', usernameVar: 'USER', passwordVar: 'PASS') {
//do some stuff with $USER and $PASS
echo "${env.USER} - ${env.PASS}"
}
请注意,您可以将任何代码放入其中withXCredenitals
以执行。withXCredentials.groovy
驻留在vars
文件夹下的我的 Jenkins 共享库中,它将使用 Jenkins 原始文件withCredentials
:
//withXCredentials.groovy
def userVar = params.usernameVar
def passwordVar = params.passwordVar
def credentialsId = params.credentialsId
withCredentials([[$class: 'UsernamePasswordMultiBinding', credentialsId: credentialsId, usernameVariable: usernameVar, passwordVariable: passwordVar]]) {
body()
}
我仍在学习高级的 groovy 东西,但我不知道如何做到这一点。
请注意:
我的问题更多是关于 groovy 和 using 的语法,而这里Closure
的答案不是我所追求的。使用该解决方案,我需要先实例化该类,然后再调用该方法。所以我试图避免做这样的事情:
new WithXCredentials(this).doSomthing(credentialsId, userVar, passwordVar)
在 Jenkins 文档中,它有一个使用闭包的示例:
// vars/windows.groovy
def call(Closure body) {
node('windows') {
body()
}
}
//the above can be called like this:
windows {
bat "cmd /?"
}
但它没有解释如何传递这样的参数
windows(param1, param2) {
bat "cmd /?"
}
看这里
解决方案
所以在挖掘互联网后,我终于找到了答案。万一有人需要同样的东西。以下代码将起作用:
// filename in shared lib: /vars/withXCredentials.groovy
def call(map, Closure body) {
def credentialsId = map.credentialsId
def passwordVariable = map.passwordVariable
def usernameVariable = map.usernameVariable
withCredentials([[$class: 'UsernamePasswordMultiBinding', credentialsId: credentialsId, usernameVariable: usernameVariable, passwordVariable: passwordVariable]]) {
echo 'INSIDE withXCredentials'
echo env."${passwordVariable}"
echo env."${usernameVariable}"
body()
}
}
有了这个,您的管道中可以有以下内容:
node('name') {
withXCredentials([credentialsId: 'some-credential', passwordVariable: 'my_password',
usernameVariable: 'my_username']) {
echo 'Outside withXCredenitals'
checkout_some_code username: "$env.my_username", password: "$env.my_password"
}
}
推荐阅读
- visual-studio-2015 - 本地主机拒绝连接错误 VIsual Studio 2015
- neo4j - Neo4j Cypher UNWIND 键
- c# - 我们如何在应用程序中使用刷新令牌?
- mongodb - $push 在 mongoDB 中不起作用
- vb.net - 四舍五入到小数点后两位
- javascript - 如何使用 jAutoCalc 插件将多行动态表写入 Mysql 数据库
- php - 想在swift 4中通过php api上传图片
- java - 如何将 Keras Tokenizer 导入 Java Deeplearning4j (DL4J)
- watson - 沃森数据提炼日期列操作
- android - 如何在本机反应中更改导航标题颜色?