Skip to content

Instantly share code, notes, and snippets.

@blackpioter
Created November 28, 2016 15:48
Show Gist options
  • Save blackpioter/c74a3baba0a61481a389e1e0d042bd48 to your computer and use it in GitHub Desktop.
Save blackpioter/c74a3baba0a61481a389e1e0d042bd48 to your computer and use it in GitHub Desktop.
jenkins-backup.sh
#!/bin/bash -xe
##################################################################################
function usage(){
echo "usage: $(basename $0) /path/to/jenkins_home jenkins.tar.gz"
}
function error_exit
{
# ----------------------------------------------------------------
# Function for exit due to fatal program error
# Accepts 1 argument:
# string containing descriptive error message
# ----------------------------------------------------------------
echo "$(basename $0): ${1:-"Unknown Error"}" 1>&2
exit 1
}
##################################################################################
readonly JENKINS_HOME=$1
readonly DEST_FILE=$2
readonly CUR_DIR=$(cd $(dirname ${BASH_SOURCE:-$0}); pwd)
readonly TMP_DIR="$CUR_DIR/tmp"
readonly ARC_NAME="jenkins-backup"
readonly ARC_DIR="$TMP_DIR/$ARC_NAME"
readonly TMP_TAR_NAME="$TMP_DIR/jenkins.tar.gz"
if [ -z "$JENKINS_HOME" -o -z "$DEST_FILE" ] ; then
usage >&2
exit 1
fi
rm -rf "$ARC_DIR" "$TMP_TAR_NAME"
mkdir -p "$ARC_DIR"
rsync -avz \
--exclude 'bin' \
--exclude 'jobs' \
--exclude 'plugins' \
--exclude 'wrapper' \
--exclude 'virtenvs' \
--exclude '.npm' \
--exclude 'caches' \
--exclude '.cache' \
--exclude 'jenkins-cli.jar' \
$JENKINS_HOME/ $ARC_DIR
function backup_jobs {
local run_in_path=$1
cd "$run_in_path"
find . -maxdepth 1 -type d | while read job_name ; do
[ "$job_name" = "." ] && continue
[ "$job_name" = ".." ] && continue
[ -d "$JENKINS_HOME/jobs/$job_name" ] && mkdir -p "$ARC_DIR/jobs/$job_name/"
rsync -avz --exclude="workspace*" --exclude="builds/[0-9]*" --exclude="pullrequests*" "$JENKINS_HOME/jobs/$job_name/" "$ARC_DIR/jobs/$job_name/"
done
chown jenkins:jenkins "$ARC_DIR/jobs"
cd -
}
if [ "$(ls -A $JENKINS_HOME/jobs/)" ] ; then
backup_jobs $JENKINS_HOME/jobs/
fi
cd "$TMP_DIR"
tar -czvf "$TMP_TAR_NAME" "$ARC_NAME"
cd -
mv -f "$TMP_TAR_NAME" "$DEST_FILE"
rm -rf "$ARC_DIR"
if [[ -e ~/python-v2/bin/activate ]]; then
source ~/python-v2/bin/activate
s3cmd put $DEST_FILE s3://BUCKET/backup/$DEST_FILE || error_exit "$LINENO: An error has occurred."
fi
exit 0
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment