Search code examples
jenkinsgroovyjenkins-job-dsl

How to use Jenkins Job DSL API in custom groovy classes


Is something like this possible, i.e. 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.


Solution

  • 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')
                }
            }
        }
    }