Skip to content

Instantly share code, notes, and snippets.

@luispabon
Created September 15, 2016 11:16
Show Gist options
  • Save luispabon/d181724ee80589d12e4b0de44b921a4f to your computer and use it in GitHub Desktop.
Save luispabon/d181724ee80589d12e4b0de44b921a4f to your computer and use it in GitHub Desktop.
#!/usr/bin/env bash
# Generate timestamped filename
TIMESTAMPED_TAG=`date +%Y-%m-%d-%H%M%S`
BACKUP_ARCHIVE="./jenkins-backup-${TIMESTAMPED_TAG}.tar.gz"
# Inconceivable race condition avoidance
if [-f $BACKUP_ARCHIVE ]; then
rm ${BACKUP_ARCHIVE}
fi
# Archive everything on jenkins but workspace, .file, .folders and m2 files, whatever these are
# If the jenkins folder changes half way through, tar will fail; retry up to 5 times
COUNTER=0
until [ $COUNTER -ge 5 ]
do
tar -czvf ${BACKUP_ARCHIVE} --exclude="workspace" --exclude=".m2" --exclude=builds --exclude=".*" /var/lib/jenkins && break
# If we get here, tar failed!
echo "Archive creation failed, retrying..."
COUNTER=$[$COUNTER+1]
sleep 15
done
# Place on s3 and cleanup
aws s3 cp ${BACKUP_ARCHIVE} s3://${S3_BUCKET}/jenkins-backups/
rm ${BACKUP_ARCHIVE}
#!/usr/bin/env bash
# Fetch backup generated from script above from s3 and restore
# This works best BEFORE you install and start jenkins for the first time
# We use this as part of our jenkins-up logic
JENKINS_CONFIG_ARCHIVE=`aws s3 ls ${S3_BUCKET}/jenkins-backups/ | sort | tail -n 1 | awk '{print $4}'`
aws s3 cp s3://${S3_BUCKET}/jenkins-backups/${JENKINS_CONFIG_ARCHIVE} .
if [ -f ${JENKINS_CONFIG_ARCHIVE} ]; then
echo "Archive found, restoring..."
tar -xvf ${JENKINS_CONFIG_ARCHIVE}
mkdir -p /var/lib/jenkins
mv var/lib/jenkins/* /var/lib/jenkins/
chown ${JENKINS_USER}:${JENKINS_GROUP} /var/lib/jenkins -Rf
rm ${JENKINS_CONFIG_ARCHIVE}
rm var -Rf
else
echo "No backups found on s3, skipping..."
fi
@kamranssuet
Copy link

Hi,
If I want to restore and backup only jobs, build history and plugins then what modification is required...

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment