ret*_*gam 5 groovy plugins class call jenkins
我对 Jenkins/Groovy 还很陌生,请多多包涵。
我正在管道 groovy 脚本中使用 DSL。DSL 实例化了一个尝试使用 Jenkins 插件的自定义类。我不断收到错误,好像系统试图以类的直接成员身份访问插件......?
Jenkins 工作:流水线脚本
@Library('lib-jenkins-util@branchname') _ // contains dsl.groovy
dsl {
x = 'value'
}
Run Code Online (Sandbox Code Playgroud)
文件: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()
}
}
Run Code Online (Sandbox Code Playgroud)
文件: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
}
}
Run Code Online (Sandbox Code Playgroud)
错误:
hudson.remoting.ProxyException:groovy.lang.MissingMethodException:没有方法签名:com.xxx.Foo.sh() 适用于参数类型:(org.codehaus.groovy.runtime.GStringImpl) 值:[curl http:/ /our-jenkins-server/xxx/api/json -user username:apitoken -o output.json]
有人可以帮助我了解我缺少什么吗?是否不能直接从自定义类中调用插件?
好吧,我找到了答案:插件,如sh,httpResponse,readJSON,等是管道的一部分,所以你必须给送管道背景下,以你的类,以便能够使用它。
我还必须将使用 Pipeline 上下文的调用移动到它们自己的方法而不是构造函数内部,以避免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
}
}
Run Code Online (Sandbox Code Playgroud)
文件: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
}
}
Run Code Online (Sandbox Code Playgroud)