Copying Jenkins jobs

When your company/project uses multiple installations of Jenkins, quite often you’d like to move build jobs from one server to another.  Jenkins does provide an extensive set of CLI command and API via HTTP. However there is nothing (yet), what would connect two build servers

bitbucketThe four scripts, which are uploaded for public use to Bitbucket, can help to copy build jobs from one server to another either individually or per entire view – tabs, which can be managed via Jenkins’ UI.

  • jnks_copy_job.sh – copies job from one server to another
  • jnks_copy_tab.sh – copies all available in the tab jobs to another server
  • jnks_del_job.sh – deletes job from the server
  • jnks_del_tab.sh – deletes all avaialbe in the tab jobs from the server

The scripts, which manage entire views, use JSON API and parse the response in order to retrieve attached to the view jobs. Then they call matching script for individual copying (deleting) of the job.

Below is incomplete fragment of jnks_copy_tab.sh script.

# Reading parameters
[ "$#" -ge 3 ] || die "Wrong parameters. $usage"
tabname=$(echo ${1/ /%20})
serverfrom=$2
serverto=$3
jenkins_cli_path=$4
# If not set, set JENKINS_HOME
if [ ! $jenkins_cli_path ]
then
 jenkins_cli_path=$(pwd)
fi

# Finding bash for copying individual jobs
copyjob=$(echo "`dirname $0`/jnks_copy_job.sh")

# finding wget or curl
http_get=$(which wget)
if [ ! $http_get ]
then
 http_get=$(which curl)
 if [ ! $http_get ]
 then
 die "Neither wget nor curl found on the path"
 else
 http_get=$(echo $http_get "--silent")
 fi
fi

# Reading jobs of the tab
echo "Retrieving data using $http_get ${serverfrom}view/$tabname/api/json?pretty=true"
eval "$http_get ${serverfrom}view/$tabname/api/json?pretty=true" | grep " \"name\" : \"" | awk -v f=" $serverfrom " -v t="$serverto " -v p="$jenkins_cli_path" -v e="$copyjob " 'BEGIN { FS = "[:,]+" }; { system(e $2 f t p) }'

Please, note that the parsing of JSON response is not 100% bulletproof. If you have any suggestion of improvements, please, do not hesitate to leave a comment or to submit a pull-request.

3 thoughts on “Copying Jenkins jobs

  1. @Vitali I fully agree. However my idea to keep these scripts as less dependent on installed applications as possible. The script for copying views has troubles with parsing names with commas. These jobs has to be copied individually.

Leave a Reply

Your email address will not be published.

Please, enter correct number below to prevent spam (required)