简体   繁体   中英

How to use Jenkins Job DSL API in custom groovy classes

Is something like this possible, ie using the JobDSL API from a class outside the main DSL script?

//main_jobdsl_script.groovy:
new JobCreator().createJob()
//JobCreator.groovy:
job("new-job") {
  steps {
    batchFile("Hello World")
  }
}

When running it I get the error

13:03:18 ERROR: No signature of method: JobCreator.job() is applicable for argument types:
(org.codehaus.groovy.runtime.GStringImpl, StartJobCreator$_createJob_closure1)
values: ["new-job", de.dbh.jobcreation.StartJobCreator$_createStartJob_closure1@374d293]

I want to avoid that the main-script gets too big and cluttered and rather divide the code into several scripts / classes.

Yes, it is possible. The current script has access to all API methods, so you need to pass it to the custom class.

//main_jobdsl_script.groovy:
new JobCreator(this).createJob()
//JobCreator.groovy:

class JobCreator {

    private final Object context

    JobCreator(Object context) {
        this.context = context
    }

    void createJob() {
        context.job('new-job') {
            steps {
                batchFile('Hello World')
            }
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM