Tuesday 12 July 2016

Create New Jenkins Job from template config xml file

Once I got the requirement of automating to create a new Jenkins job.  I took config XML file from base Jenkin’s job and edited the config XML, the values specific to that job into constants, and saved this config as a template. I have written a shell script which will create a new config.XML out of template config and modify the constants accordingly. By this way, you can automate the creation of new Jenkins job.
Below Shell script helps to automatically create a new Jenkins Job from template config XML file.
Createjob.sh
#!/bin/bash
set +x

# To create a job
function create_job {
 mkdir $1
 cp template.xml $1
 mv ./$1/template.xml ./$1/config.xml
 echo Job $1 is created. 
}

#Modify TEMPLATE_SERVER, TEMPLATE_WORKSPACE keywords from template.xml are replaced from 
test.properties
function modify_job {
 . ./test.properties
 echo TEMPLATE_SERVER is replaced with $servername
 echo TEMPLATE_WORKSPACE is replaced with $workspace
 sed -i -- "s/TEMPLATE_SERVER/$servername/g" ./$1/*
 sed -i -- "s/TEMPLATE_WORKSPACE/$workspace/g" ./$1/*
}

# Need to reload disk for new job to be visible in the Jenkins.
function reload_disk {
 $JAVA_HOME/bin/java -jar jenkins-cli.jar -s http://testjenkins.com/ reload-configuration --username testuser --password-file myPwd.txt
}

usage(){
 echo "Usage: $0 filename"
 exit 1
}

[[ $# -eq 0 ]] && usage

# Just to check whether the job exists or not.
if [ -d "$1" ]; then
 echo "job $1 already exists"
 exit
fi
create_job $1
modify_job $1
reload_disk
We can store all properties into a file. Below are the example properties stored in the properties file.
test.properties
servername=testserver20
workspace=testworkspace20

0 Comments:

Post a Comment

Subscribe to Post Comments [Atom]

<< Home