Jenkins Job DSL with a Jenkins SeedJob




Hi all, today I thought of discussing how we can make use of a single Jenkins seed job to programmatically create other jobs as needed.

So let's look at how we can use groovy scripting to create a simple Jenkins job. Jenkins provides a nice UI that helps us to configure build jobs for our project. However, when the number of builds grows, to configuring via UI may become a tedious task.

The objective here is to enable job creation programmatically rather than a user having to manually configure it from the UI. In the below scenario we will see how we can create a Jenkins Seed job that will help create other jobs as required.

The groovy code shown below is a basic example of how we can create a Jenkins job. The code has some important sections.
  1. Job: this section gives the unique name that we have to give for the job that we create.
  2. Description: A useful description of the job that we are going to create.
  3. SCM: the GIT repo URL and the branch name which has the code.
  4. Trigger: The CRON job for the task to be executed.
  5. Steps: The maven command.
  6. Publisher: The type of artifact we want to archive once build is successful.

job("Maven-project-via-dsl") {
    description("maven project on ${new Date()}")
    scm {
        git("https://github.com/shavantha/helloworld.git", 'master')
    }
    triggers {
        scm('* * * * *')
    }
    steps {
        maven('clean package', 'pom.xml')
    }
    publishers {
        archiveArtifacts '**/*.war'
    }
} 
 
 
To try this out, we need to first install the plugin JobDSL which can be found under the available plugins when we access the manage Jenkins option.  Codes are normally maintained in a source code repository such as the GitHub. In this post, I have added the above code to GitHub. In GitHub, we need to follow the below 2 steps to configure the seed job. A seed job in Jenkins is one that runs a script and generates another new job.

Step1:Once the above plugin is installed we need to create a new item in Jenkins. In this, we need to first give the git repo location as shown in the below image. Next


Step2: Under build-actions, we need to specify the path from which our grovy script code needs to be downloaded




Once the above two steps are configured, our Jenkins seed job is ready to be executed. To run this navigate to the job and click on "BuildNow". This will first attempt to run the pull the script from the
GitHub repo but will fail because the permission is yet not granted to execute the script within Jenkins.  To overcome this we need to move into manage Jenkins and approve the script under in-process script approval. Once this permission is granted you would be able to see a new job created based on the configurations given within the groovy script.


Comments