Jenkins : One Jobs to Create them All [EN]

Jenkins : One Jobs to Create them All [EN]

2017-04-06 0 Par seuf

Today, I will talk about a Jenkins plugin called  « Jenkins Job DSL. »

It’a a plugin that allow you to create jenkins jobs from a jenkins job !

You just have to create a grovvy script to describe your job.

Install the Job DSL Plugin on Jenkins

To install the plugin, download the latest release here, then install it (Administration > Plugin management)

Create a « seed » job

The next step is to create a seed job. For this, create a new « free-style » job, and select :

  • Source code : clone your git repository where your DSL groovy scripts will be stored.
  • Build : Select « process Job DSL » build type.
    • Look on filesystem : « dsl/*.groovy »

Create Groovy Jobs

Now, create a git repository whith some groovy scripts to define all your jenkins jobs:

Here is an example of groovy script to deploy projects with ansible :

job('ansible_deploy') {
    description('Ansible deploy')

    wrappers {
        colorizeOutput()
        preBuildCleanup()
    }

    parameters {
        stringParam('GIT_REPO', 'https://git.company.com/project/ansible.git', 'Nom du repo git')
        stringParam('GIT_BRANCH', 'master', 'Git branch')       
        stringParam('ANSIBLE_INVENTORY', 'inventory/env/hosts', 'Ansible inventory file')
        stringParam('ANSIBLE_TAGS', '', 'Ansible tags')       
        stringParam('ANSIBLE_LIMITS', '', 'Ansible limits') 
        stringParam('ANSIBLE_USER', 'deploy', 'Ansible user')
        stringParam('ANSIBLE_EXTRA_VARS', '', 'Ansible extra vars')
    }

    environmentVariables {
        keepSystemVariables(true)
        keepBuildVariables(true)
    }

    scm {
        git($GIT_REPO, $GIT_BRANCH)
    }

    steps {
        shell(readFileFromWorkspace('shell/ansible_deploy.sh'))
    }
}

This job will clone a git repo where ansible roles and playbooks are stored.

Then the shell script will execute the ansible-playbook command with the corrects options according to the specified parameters in the job.

The script can also install additional roles with ansible galaxy

ansible-galaxy install -r requirements.yml
ansible-playbook -i $ANSIBLE_INVENTORY -u $ANSIBLE_USER -e "$ANSIBLE_EXTRA_VARS" -l "$ANSIBLE_LIMITS" -t "$ANSIBLE_TAGS" play.yml

 

Now you can create all your jobs with groovy script to do whatever you want ! (build maven stuff, deploy with ansible, package projects, generate documentation, etc..)

The documentation is very complete :

https://github.com/jenkinsci/job-dsl-plugin/wiki

https://jenkinsci.github.io/job-dsl-plugin/#path/job

Run the Seed Job

Once all your jobs scripts are pushed to your « jenkins-dsl-jobs » git repository, you can run the seed job.

The advantages are :

  • All your jenkins jobs are versionned, no more broken job because someone have modified it
  • Your Jenkins users don’t need write permission on jenkins jobs !