From plain Groovy to Jenkins Job DSL: A Quantum Jump

Creating Jenkins instances programmatically with Groovy can be quite a challenge. A while ago we started with the One-Click Jenkins Setup. The biggest challenge was to create the initial jobs and working through the various Jenkins APIs.

Lately we moved to the Jenkins Job DSL Plugin.

There is a fantastic documentation available: Jenkins Job DSL API (online). Once the plugin is up and running in your local Jenkins your can access the Jenkins Job DSL API (your Jenkins) locally, too.

Our overall setup didn't change much.

We start FROM jenkinsci/jenkins

FROM jenkinsci/jenkins:2.61

....
ADD jobs.groovy /var/jenkins_home/

RUN /usr/local/bin/install-plugins.sh job-dsl:1.63 git:3.3.0 workflow-aggregator:2.5

COPY create-initial-jobs-with-dsl.groovy /var/jenkins_home/init.groovy.d/

We bootstrap the job creation in create-initial-jobs-with-dsl as described in Initializing Jenkins 2.0 with pipeline in init.groovy.d script:

import javaposse.jobdsl.dsl.DslScriptLoader
import javaposse.jobdsl.plugin.JenkinsJobManagement

def jobDslScript = new File('/var/jenkins_home/jobs.groovy')
def workspace = new File('.')

def jobManagement = new JenkinsJobManagement(System.out, [:], workspace)

new DslScriptLoader(jobManagement).runScript(jobDslScript.text)

Within the jobs.groovy we describe all our jobs:

pipelineJob('planets-homepage') {
  definition {
    cpsScm {
      scm {
        git {
          remote {
            credentials('planets-homepage_id_rsa')
            url('git@github.com:datenkollektiv/planets-homepage.git')
          }
        }
      }
      scriptPath('Jenkinsfile')
    }
  }
  scm {
    git {
      remote {
        credentials('planets-homepage_id_rsa')
        url('git@github.com:datenkollektiv/planets-homepage.git')
      }
    }
  }
  triggers {
      cron('@midnight')
  }
}

Easy readable, good documentation, ... reproducible Jenkins setups made easy. I like it.

If you got so far you might also like our other Jenkins related posts: