Created
July 20, 2022 15:44
-
-
Save gustavomcarmo/5d6640b89eeddf8bd3dd841b862944de to your computer and use it in GitHub Desktop.
Jenkins backup by exporting jobs definitions to XML files.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/python3 | |
from datetime import datetime | |
import logging | |
import os | |
import requests | |
def get_params(): | |
if 'JENKINS_URL' not in os.environ or 'JENKINS_ADMIN_USERNAME' not in os.environ or 'JENKINS_ADMIN_PASSWORD' not in os.environ: | |
raise ValueError("The following environment variables are required: JENKINS_URL, JENKINS_ADMIN_USERNAME and JENKINS_ADMIN_PASSWORD.") | |
return os.environ['JENKINS_URL'], os.environ['JENKINS_ADMIN_USERNAME'], os.environ['JENKINS_ADMIN_PASSWORD'] | |
def handle_job(url, auth, path): | |
if not os.path.exists(path): | |
job_request = requests.get(url.replace('http://', 'https://') + '/config.xml', auth=auth) | |
if job_request.status_code == 200: | |
file = open(path, 'w') | |
file.write(job_request.text) | |
file.close() | |
logging.info('Job %s exported.', path) | |
job_request.close() | |
else: | |
logging.warning('Job %s already exported.', path) | |
def handle_folder(url, auth, path): | |
folder_request = requests.get(url.replace('http://', 'https://') + '/api/json', auth=auth) | |
if folder_request.status_code == 200: | |
for job in folder_request.json()['jobs']: | |
if job['_class'] == 'com.cloudbees.hudson.plugins.folder.Folder': | |
current_path = path + '/' + job['name'] | |
if not os.path.exists(current_path): | |
os.mkdir(current_path) | |
logging.info('Folder %s created.', current_path) | |
else: | |
logging.warning('Folder %s already created.', current_path) | |
handle_folder(job['url'], auth, current_path) | |
else: | |
current_path = path + '/' + job['name'] + '.xml' | |
handle_job(job['url'], auth, current_path) | |
folder_request.close() | |
def main(): | |
jenkins_url, jenkins_admin_username, jenkins_admin_password = get_params() | |
logging.basicConfig(level=logging.INFO, format="%(asctime)s: %(levelname)s - %(message)s") | |
logging.info('Started processing') | |
ts = int(datetime.timestamp(datetime.now())) | |
backup_dir = './jenkins-backup-' + str(ts) | |
os.mkdir(backup_dir) | |
os.chdir(backup_dir) | |
logging.info('Backup folder: %s', backup_dir) | |
handle_folder(jenkins_url, (jenkins_admin_username, jenkins_admin_password), '.') | |
logging.info('Ended processing') | |
if __name__ == "__main__": | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment