如何在类中使用 Jenkins 插件?

5

我对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 username:apitoken -o output.json]

请问有人能帮我理解我错过了什么吗?我们不能直接从自定义类中调用插件吗?

1个回答

9
好的,我找到了答案:像shhttpResponsereadJSON等插件都是Pipeline的一部分,因此您必须将pipeline上下文发送给您的类,以便能够使用它。
我还不得不将使用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
    }
}

文件名: 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
    }
}

1
https://jenkins.io/doc/book/pipeline/shared-libraries/#accessing-steps - Rustam Tagaev

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接