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.

1# Reading parameters
2[ "$#" -ge 3 ] || die "Wrong parameters. $usage"
3tabname=$(echo ${1/ /%20})
4serverfrom=$2
5serverto=$3
6jenkins_cli_path=$4
7# If not set, set JENKINS_HOME
8if [ ! $jenkins_cli_path ]
9then
10 jenkins_cli_path=$(pwd)
11fi
12 
13# Finding bash for copying individual jobs
14copyjob=$(echo "`dirname $0`/jnks_copy_job.sh")
15 
16# finding wget or curl
17http_get=$(which wget)
18if [ ! $http_get ]
19then
20 http_get=$(which curl)
21 if [ ! $http_get ]
22 then
23 die "Neither wget nor curl found on the path"
24 else
25 http_get=$(echo $http_get "--silent")
26 fi
27fi
28 
29# Reading jobs of the tab
30echo "Retrieving data using $http_get ${serverfrom}view/$tabname/api/json?pretty=true"
31eval "$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)