我是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:无方法签名: com.xxx.Foo.sh()适用于参数类型:(org.codehaus.groovy.runtime.GStringImpl)值:[curl http://our-jenkins-server/xxx/api/json -user用户名:apitoken -o output.json]
有没有人能帮我弄明白我错过了什么?在自定义类中直接调用插件是不可能的吗?
发布于 2018-07-25 07:06:26
好的,我找到了答案:sh
、httpResponse
、readJSON
等插件都是管道的一部分,所以你必须将管道上下文发送给你的类才能使用它。
我还必须将使用管道上下文的调用移动到它们自己的方法中,而不是在构造函数中,以避免导致构建失败的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
}
}
https://stackoverflow.com/questions/51508267
复制相似问题