Jenkins - backup and restore jobs

Backup / Restore jobs

Jenkins provides a quick way for us to backup job definitions through its API. Using any compatible HTTP client (such as your browser), you can retrieve the job configuration in the .xml  format. Note that the URL to the configuration file depends on the Jenkins file location.

Jenkins job not in sub-folders:
https://[jenkins_server]/job/[jenkins_job_name]/config.xml

Jenkins job in sub-folder”dev”
https://[jenkins_server]/job/dev/config.xml

Restore Jenkins Jobs

Using the same Jenkins API, we can restore a job using any HTTP client that is able to send POST requests. To restore a job, copy the content of the job definition file into the HTTP request body and make your request to the job you want to restore.

1
2
https://[jenkins_server]/job/[jenkins_job_name]/config.xml  -POST
<jenkins_job_xml_content>

Demo: Backup Jenkins job tool

JenkinsXmlRetriever is a tool build to retrieve all Jenkins job definition from a Jenkins server (including nested Jenkins folders). The tool is written in C#  .Net Core and can be run in Windows and Linux environments.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
using Microsoft.Extensions.Configuration;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Text;

namespace JenkinsXmlRetriever
{
class Program
{
static void Main(string[] args)
{
var jenkinsDownloadManager = new JenkinsDownloadManager("jenkins_user_id:jenkins_api_token");
jenkinsDownloadManager.BackupJenkinsJobs(
jenkinsDownloadManager.GetDownloadListFrom()
);
}
}
public class BackupConfig
{
private readonly IConfigurationRoot ConfigRoot = null;
public BackupConfig() : this("appsettings.json") { }
public BackupConfig(string fileName)
{
var builder = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile(fileName);

ConfigRoot = builder.Build();

}
public string OuptutBasePath => GetValue("OuptutBasePath", Environment.CurrentDirectory);
public string BackupListFilePath => GetValue("BackupListFilePath", string.Empty);
private string GetValue(string key, string defaultValue)
{
return string.IsNullOrEmpty(ConfigRoot[key]) ? defaultValue : ConfigRoot[key];
}
}
public class JenkinsDownloadManager
{
private readonly BackupConfig BackupConfig;
private readonly string AuthInfo;
string EncodedAuthInfo => Convert.ToBase64String(Encoding.ASCII.GetBytes(AuthInfo));
public JenkinsDownloadManager(string jenkinsAuthTkn)
: this(new BackupConfig())
{
this.AuthInfo = jenkinsAuthTkn;
}
public JenkinsDownloadManager(BackupConfig config)
{
BackupConfig = config;
}
public List&lt;JenkinsPageData> GetDownloadListFrom(string filename = "")
{
// File name override if provided
filename = string.IsNullOrWhiteSpace(filename) ? BackupConfig.BackupListFilePath : filename;
if (!File.Exists(filename))
{
throw new FileNotFoundException(filename);
}

var jenkinsJobData = new List&lt;JenkinsPageData>();
var jobUrls = File.ReadAllLines(filename);
foreach (var item in jobUrls)
{
jenkinsJobData.Add(new JenkinsPageData { DownloadUrl = item });
}
return jenkinsJobData;
}
public void BackupJenkinsJobs(List&lt;JenkinsPageData> dataRows)
{
dataRows.ToList().ForEach(dataRow =>
{
var folderDefinition = this.BackupJenkinsJob(dataRow);
var jenkinsDirectory = JsonConvert.DeserializeObject&lt;JenkinsJson>(folderDefinition);
var path = Path.Combine(BackupConfig.OuptutBasePath, jenkinsDirectory.JenkinsFolderName);
GetNestedJobs(jenkinsDirectory.JenkinsJobs, path);
});
}
protected string BackupJenkinsJob(JenkinsPageData jenkinsJob)
{
string rtnContent = string.Empty;
try
{
var httpClient = new HttpClient();
httpClient.DefaultRequestHeaders.Add("Accept", "text/xml");
httpClient.DefaultRequestHeaders.Add("Authorization", string.Format("Basic {0}", EncodedAuthInfo));
var httpContent = httpClient.GetStringAsync(jenkinsJob.DownloadUrl);
rtnContent = httpContent.Result;
}
catch (Exception ex)
{
Console.WriteLine("Error retrieving:url='{0}', err='{1}'", jenkinsJob.DownloadUrl, ex.ToString());
}

return rtnContent;
}
protected void GetNestedJobs(JenkinsJob[] jenkinsJobs, string outputDirectory)
{
jenkinsJobs.ToList().ForEach(jenkinsJob =>
{
var newPath = Path.Combine(outputDirectory, jenkinsJob.Name);
if (jenkinsJob.IsJenkinsFolder)
{
var jpd = new JenkinsPageData { DownloadUrl = string.Format("{0}/api/json", jenkinsJob.Url) };
var x = this.BackupJenkinsJob(jpd);
var y = JsonConvert.DeserializeObject&lt;JenkinsJson>(x);
GetNestedJobs(y.JenkinsJobs, newPath);
}
if (jenkinsJob.IsJenkinsJob)
{
var jpd = new JenkinsPageData { DownloadUrl = string.Format("{0}/config.xml", jenkinsJob.Url) };
var jobDefinition = this.BackupJenkinsJob(jpd);

Directory.CreateDirectory(newPath);

File.AppendAllText(Path.Combine(outputDirectory, jenkinsJob.Name, jpd.TargetRelativePath), jobDefinition);
}
});
}

}
public class JenkinsPageData
{
public bool IsVersioned { get; set; } = true;
public string DownloadUrl { get; set; }
public string TargetRelativePath
{
get
{
if (IsVersioned)
{
var replacementStr = string.Concat("_", DateTime.UtcNow.ToString("yyyyMMddhhmmss"), ".xml");
return Path.Combine(JenkinsJobname, JenkinsJobDefinition.Replace(".xml", replacementStr));
}

return Path.Combine(JenkinsJobname, JenkinsJobDefinition);
}
}
string JenkinsJobname
{
get
{
if (!string.IsNullOrEmpty(DownloadUrl))
{
var request = new Uri(DownloadUrl);
if (request != null &amp;&amp; request.Segments.Length > 2)
{
return request.Segments[request.Segments.Length - 2].TrimEnd('/');
}
}

throw new InvalidDataException(string.Format("Invalid download Url='{0}'", DownloadUrl));
}
}
string JenkinsJobDefinition
{
get
{
if (!string.IsNullOrEmpty(DownloadUrl))
{
var request = new Uri(DownloadUrl);
if (request != null &amp;&amp; request.Segments.Length > 2)
{
return request.Segments.Last();
}
}

throw new InvalidDataException(string.Format("Invalid download Url='{0}'", DownloadUrl));
}
}
}
public class JenkinsJson
{
[JsonProperty("name")]
public string JenkinsFolderName { get; set; }
[JsonProperty("jobs")]
public JenkinsJob[] JenkinsJobs { get; set; }
}
public class JenkinsJob
{
[JsonProperty("_class")]
public string Class { get; set; }
[JsonProperty("name")]
public string Name { get; set; }
[JsonProperty("url")]
public string Url { get; set; }
public bool IsJenkinsJob => string.Equals(this.Class, "hudson.model.FreeStyleProject", StringComparison.InvariantCultureIgnoreCase);
public bool IsJenkinsFolder => string.Equals(this.Class, "com.cloudbees.hudson.plugins.folder.Folder", StringComparison.InvariantCultureIgnoreCase);
}
}

The project configuration file: appsettings.json

1
2
3
4
{
"OuptutBasePath": "C:\\JenkinsXmlRetriever\\",
"BackupListFilePath": "C:\\JenkinsXmlRetriever\\JenkinsJobBackupList.txt"
}

JenkinsJobBackupList.txt, contains the top level Jenkins folders you would like to backup. api/json**‘** is added to the end of the URL. The URL should show JSON data when browsed:

1
https://[jenkins_server]/jenkins_directory/api/json 

Download Source Code