我对 Jenkins/Groovy 还很陌生,请多多包涵。
我正在管道 groovy 脚本中使用 DSL。 DSL 实例化了一个尝试使用 Jenkins 插件的自定义类。我不断收到错误,好像系统试图以类的直接成员身份访问插件......?
Jenkins 工作:流水线脚本
@Library('lib-jenkins-util@branchname') _ // contains dsl.groovy
dsl {
x = 'value'
}
文件:dsl.groovy
def call(body) {
def config = [:]
body.resolveStrategy = Closure.DELEGATE_FIRST
body.delegate = config
body()
node('node-name') {
stage('Stage 1') {
def f = new Foo()
}
}
文件:Foo.groovy
class Foo implements Serializable {
Foo() {
// fails below
sh "curl http://our-jenkins-server/xxx/api/json -user username:apitoken -o output.json"
json = readJSON file: output.json
}
}
错误:
hudson.remoting.ProxyException: groovy.lang.MissingMethodException: No signature of method: com.xxx.Foo.sh() is applicable for argument types: (org.codehaus.groovy.runtime.GStringImpl) values: [curl http://our-jenkins-server/xxx/api/json -user username:apitoken -o output.json]
有人可以帮助我了解我缺少什么吗?是否不能直接从自定义类中调用插件?
最佳答案
好的,我找到了答案:插件如 sh
, httpResponse
, readJSON
等是管道的一部分,因此您必须发送 管道上下文 到您的类(class),以便能够使用它。
我还必须将使用管道上下文的调用移动到它们自己的方法而不是在构造函数内部以避免 CpsCallableInvocation
导致构建失败的问题。
文件:dls.groovy
def call(body) {
def config = [:]
body.resolveStrategy = Closure.DELEGATE_FIRST
body.delegate = config
body()
node('node-name') {
stage('Stage 1') {
def f = new Foo(this) // send pipeline context to class
}
}
文件:Foo.groovy
class Foo implements Serializable {
def context
Foo(context) {
this.context = context
}
def doTheThing() {
this.context.sh "curl http://our-jenkins-server/xxx/api/json -user username:apitoken -o output.json"
def json = this.context.readJSON file: output.json
}
}
关于class - 如何在类中使用 Jenkins 插件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51508267/