Monday, October 17, 2016

Jenkins - How to Automate CI and CD Pipeline Use DSL (1)

This is a simple tutorial to show you how to achieve CI and CD automation in Jenkins through DSL (Domain-specific language, Groovy-based). Jenkins is a great tool for automating your build and deployment pipelines. If you are not familiar with Jenkins, go to (https://jenkins.io/) for more information, you need somewhat Jenkins background to go through this tutorial.

In a highlevel description, you define jobs (or pipelines) in jenkins for build, test, deployment and rollback, then Jenkin do the work for you. For small number of jobs, that's okay. But for large number of jobs, for example, you are dealing with microservices, if you setup and configure jobs in manual, you will be in a bit trouble. With hundreds or thousands of job, pipeline definitions, it is very hard to keep track of every configuration manually. As the number of jobs keep increasing in Jenkins, management becomes a growing pain. That's where the job DSL comes to the rescure.

In this tutorial, I will show you how to build a build pipeline by using Jenkins DSL.

Requirements:
- Jenkins 1.x or 2.x
- Jenkins Nested View Plugin
- Jenkins Job DSL Plugin (https://wiki.jenkins-ci.org/display/JENKINS/Job+DSL+Plugin)
- Jenkins Pipeline

Create a simple job from DSL
First of all, we need a seed job, the purpose of this seed job is to process DSL script to generate other Jenkins Jobs

1. Create seed job from Jenkins UI and call it "jerkins-seed"


2. Go to "Build" section, select "Process Job DSLs" -> "Use the provided DSL script", and paste the following Groovy script:


freeStyleJob('jenkins-dsl-test1') {
  scm {
    git {
      remote {
        url('https://github.com/tonylixu/jenkins-dsl')
      }
      branch('master')
    }
  }
  triggers {
     scm('H/15 * * * *')
  }

  steps {
    maven {
      mavenInstallation('3.1.1')
      goals('clean install')
    }
  }
}

The script is also available at:
https://github.com/tonylixu/jenkins-dsl

In the above DSL script, we define a Jenkins job named "jenkins-dsl-test1", which contains a source control section with a Github repository, master branch. This job use maven for actual build, the maven command being used it very simple, just "mvn clean install", and it triggers every 15 minutes. Save the job and "Build Now", you will see something like this in the console output:

Processing provided DSL script
Added items:
    GeneratedJob{name='jenkins-dsl-test1'}
Finished: SUCCESS

And check out the Jenkins UI:




So there you go, you just generated a jenkins job by calling a Jenkins DSL script. A good idea is to SCM (source code management) this script, you can basically replicate this job in any Jenkins master!

Get the idea? Now let's do something really cool!

Jenkins - How to Automate CI and CD Pipeline Use DSL (2) (Coming soon)

No comments: