falc0nit3
falc0nit3

Reputation: 1009

Passing closures from a class in Groovy/Jenkins

I'm trying to create a JobGenerator class that will pass a build step down to the calling instance. I'm running into an issue where if I get this error when I try to run this:

hudson.remoting.ProxyException: groovy.lang.MissingMethodException: No signature of method: org.jenkinsci.plugins.workflow.cps.CpsClosure2.build() is applicable for argument types: (java.util.LinkedHashMap) values: [[job:FooJob]]

class BuildGenerator implements Serializable {     

static def generateJob() {
    return  [
            "TestJob",
            { ->
                build(
                        job: 'FooJob'
                )
            },
    ]
  }        
}        

node(){
    def tasks = [:]
    def label
    def task

    stage("Build") {
        def generator = new BuildGenerator()            
        tasks["Testing"] = generator.generateJob()[1]
        parallel tasks
    }
}

If I remove the generateJob function outside of the class then it works fine. What am I doing wrong with closures here? I'm new to groovy/jenkins world.

Upvotes: 1

Views: 1207

Answers (1)

Szczad
Szczad

Reputation: 826

Well... This is the way Groovy/Jenkins pipeline work. build is available inside node as the rest of steps and functions. If you wish to access these you have to pass the CPS instance to the method, like this (or use constructor to pass the instance only once):

class BuildGenerator implements Serializable {     

static def generateJob(script) {
    return  [
            "TestJob",
            { ->
                script.build(
                        job: 'FooJob'
                )
            },
    ]
  }        
}        

node(){
    def tasks = [:]
    def label
    def task

    stage("Build") {
        def generator = new BuildGenerator()            
        tasks["Testing"] = generator.generateJob(this)[1]
        parallel tasks
    }
}

Upvotes: 2

Related Questions