Skip to content

Instantly share code, notes, and snippets.

@varunchandak
Last active June 10, 2022 12:11
Show Gist options
  • Save varunchandak/7aad6ae3d7099c21a4aead52f084107c to your computer and use it in GitHub Desktop.
Save varunchandak/7aad6ae3d7099c21a4aead52f084107c to your computer and use it in GitHub Desktop.
Automated Jenkins Upgrade Script
#!/bin/bash
# This script will auto upgrade jenkins to latest stable version if found.
export EPOCH_DATE="$(date +%s)"
export JENKINS_UPGRADE_URL="http://mirrors.jenkins-ci.org/war-stable/latest/jenkins.war"
export JENKINS_DIR="/usr/share/java"
export TEMP_DIR="/tmp/jenkins-upgrade-"$EPOCH_DATE"/"
export WEBHOOK="https://hooks.slack.com/services/XXXX/YYYY/ZZZZZ"
# Create temp directory
mkdir "$TEMP_DIR"
# download latest stable war file to temp directory
wget "$JENKINS_UPGRADE_URL" -P "$TEMP_DIR"/ || exit 1
# Check MD5 of new and old jenkins
export NEW_JENKINS_MD5="$(md5sum /tmp/jenkins-upgrade-"$EPOCH_DATE"/jenkins.war | awk '{print $1}')"
export OLD_JENKINS_MD5="$(md5sum "$JENKINS_DIR/jenkins.war" | awk '{print $1}')"
if [ "$NEW_JENKINS_MD5" != "$OLD_JENKINS_MD5" ]; then
echo "Jenkins Upgrade Available. Upgrading..."
curl -X POST -H 'Content-type: application/json' --data '{"text":"Jenkins Upgrade Available. Upgrading..."}' "$WEBHOOK"
while true; do
# stop the jenkins service
if systemctl stop jenkins.service 2> /dev/null; then
# move the current war file to backup
cp "$JENKINS_DIR"/jenkins.war "$JENKINS_DIR"/jenkins.war-"$EPOCH_DATE"
# move the latest war file to current
cp "$TEMP_DIR"/jenkins.war "$JENKINS_DIR"/
# start the jenkins service
systemctl start jenkins.service
sleep 5
# check connectivity to check service is running properly, else revert to older version
if echo -e '\x1dclose\x0d' | telnet localhost 8080 > /dev/null 2>&1; then
echo "Jenkins Started Successfully"
curl -X POST -H 'Content-type: application/json' --data '{"text":"Jenkins Started Successfully"}' "$WEBHOOK"
break
else
echo "Jenkins Failed to start. Manual intervention required."
curl -X POST -H 'Content-type: application/json' --data '{"text":"Jenkins Failed to start. Manual intervention required."}' "$WEBHOOK"
break
fi
else
echo "Unable to stop Jenkins for upgrade. Retrying in 5 mins"
curl -X POST -H 'Content-type: application/json' --data '{"text":"Unable to stop Jenkins for upgrade. Retrying in 5 mins."}' "$WEBHOOK"
sleep 5
fi
done
else
echo "No Upgrade available."
fi
# Removing temporary stuff
rm -rf "$TEMP_DIR"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment