class - 如何在类中使用 Jenkins 插件?

标签 class jenkins groovy plugins call

我对 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/

相关文章:

tomcat - Jenkins 在重新安装后保留设置

git - 如何在 Groovyscript 中导入 Jenkins 插件?

bash - Jenkins 为所有作业删除早于最新 20 个构建的构建

javascript - 检查是否使用 jQuery/JavaScript 将特定对象加载到 DOM 中?

c++ - 如何创建另一个类结构的 vector ? (C++ 11)

javascript - 第二个参数 Object.create

php - 在php中获取类的所有静态属性的最简单方法

jenkins - MSBuild 不使用 PublishProfile 复制文件

Jenkins Jobs DSL - 如何定义属性文件

xml - Groovy:使用 GPathResult.appendNode(node) 合并两个 XML 文件不起作用