1
votes

I'm trying to fully automate the creation of Jenkins. I got most of the setup working using groovy scripts. My last hurdle is creating a job using the DSL. I'm able to create the job using xml via:

import jenkins.model.*

def jobName = "jobname"
String configXml = new File('/jobname.xml').getText('UTF-8')
def xmlStream = new ByteArrayInputStream( configXml.getBytes() )
Jenkins.instance.createProjectFromXML(jobName, xmlStream)

However, the XML file is hard to maintain and not easy to understand. So I wanted to switch to use DSL syntax, but I can't fix an API to replace createProjectFromXML(...) with something like createPrjectFromDSL?

My question is how to create a new job using DSL? I got this part working, thank you.

However my next question is where do I put this file so Jenkins will create the job on startup? When i try to copy it to /var/jenkins_home/init.groovy.d I get the following exception on startup:

WARNING: Failed to run script file:/var/jenkins_home/init.groovy.d/neoconfig-dsl.groovy groovy.lang.MissingMethodException: No signature of method: neoconfig-dsl.job() is applicable for argument types: (java.lang.String, neoconfig-dsl$_run_closure1) values: [neo, neoconfig-dsl$_run_closure1@7d799f93] Possible solutions: run(), run(), any(), wait(), grep(), dump()

1
You can create, a project that will fetch DSL jobs from remote repo and build them.Opal
I think is something I looking for. Can you elaborate a bit more? My goal is to automate the creation of all my jobs using the job DSL.Gerb

1 Answers

4
votes

The Jenkins Job DSL plugin provides exactly, what you seem to be looking for: A (Groovy-based) DSL to define jobs.

A simple job definition looks as follows:

def repo = 'DSL-Tutorial-1-Test'
job(repo) {
    scm {
        git('git://github.com/quidryan/aws-sdk-test.git')
    }
    triggers {
        scm('H/15 * * * *')
    }
    steps {
        maven('-e clean test')
    }
}

EDIT: To automatically start this job after definition, add the following code:

// automatically queue the job after the initial creation
if (!jenkins.model.Jenkins.instance.getItemByFullName(repo)) {
  queue(repo)
}

A complete example of a setup that creates a self-bootstrapping docker container can be found in tknerr/jenkins-pipes-infra. I am using (mostly) the same approach here.