【问题标题】:How can I use a Jenkins plugin inside a class?如何在类中使用 Jenkins 插件?
【发布时间】:2019-01-01 15:29:30
【问题描述】:

我是 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]

有人可以帮助我了解我缺少什么吗?是不是不能在自定义类中直接调用插件?

【问题讨论】:

    标签: class jenkins groovy plugins call


    【解决方案1】:

    好的,我找到了答案:shhttpResponsereadJSON 等插件是 Pipeline 的一部分,因此您必须将 pipeline context 发送到您的班级为了能够使用它。

    我还必须将使用管道上下文的调用移动到它们自己的方法中,而不是在构造函数中,以避免导致构建失败的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
        }
    }
    
    猜你喜欢
    • 2012-09-07
    • 1970-01-01
    • 2016-10-20
    • 2020-03-29
    • 2014-11-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-12-06
    相关资源
    最近更新 更多