Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Purge database script that reports back to Slack .... Make sure to put in your SLACK WEBHOOK URL!!!!
#!/bin/bash
#
# Script to purge old database backups
# Run via cron job
#
#########################################
#########################################
#
# Config section
#
#########################################
BACKUP_DIR="/data/db-nightly-backups"
DAYS_TO_KEEP=15
#########################################
#
# Slack Function
#
#########################################
SLACK_URL="PUT YOUR SLACK WEBHOOK HERE"
function slack_post_good() {
curl -H "Content-type:application/json" \
-X POST -d \
'{
"channel":"#dev_ops",
"username" : "ESXi",
"icon_emoji" : ":esxi:",
"attachments" : [
{
"fallback": "DB Purge Succeeded",
"color" : "good",
"fields" : [
{
"title" : "DB Purge Succeded",
"value" : ".\nDB purge succeeded\nmsg: '"$1"'",
"short" : "true"
},
{
"title" : "'"$2"'",
"value" : ".\n'"$3"'",
"short" : "true"
}
]
}
]
}
' $SLACK_URL
}
function slack_post_bad() {
curl -H "Content-type:application/json" \
-X POST -d \
'{
"channel":"#dev_ops",
"username" : "ESXi",
"icon_emoji" : ":esxi:",
"attachments" : [
{
"fallback": "Alert!: DB Purge Failed",
"color" : "danger",
"fields" : [
{
"title" : "Alert!: DB Purge Failed",
"value" : ".\nDB Purge failed\nmsg: '"$1"'",
"short" : "true"
}
]
}
]
}
' $SLACK_URL
}
#########################################
#
# Delete Old Datbases older than $DAYS_TO_KEEP
#
#########################################
# for testing you can switch mtime for days to mmin for minutes
NUM_FILES_REMOVED=`find $BACKUP_DIR -maxdepth 1 -mtime +$DAYS_TO_KEEP -name "*.database.*" | wc -l`
# for testing you can switch mtime for days to mmin for minutes
if ! find $BACKUP_DIR -maxdepth 1 -mtime +$DAYS_TO_KEEP -name "*.database.*" | xargs -I{} rm -rf {};
then
echo "DB purge failed. Exiting." 1>&2
slack_post_bad "DB purge failed on DIR\n$BACKUP_DIR"
exit 3
fi
#########################################
#
# purge Complete now notify!
#
#########################################
DB_DIR_INFO=`df -h $BACKUP_DIR | sed 's/.$/\\\n/g' | tr -d "\n"`
slack_post_good "Database Purge Complete\nDAYS_KEPT: $DAYS_TO_KEEP\nFILES_REMOVED: $NUM_FILES_REMOVED" \
"BACKUP FOLDER % Left" \
"$DB_DIR_INFO"
echo ""
echo "================================"
echo ""
echo " DATABASE purge Complete"
echo ""
echo " Databases Removed : $NUM_FILES_REMOVED"
echo ""
echo " Only keeping $DAYS_TO_KEEP DAYS"
echo "================================"
exit 0
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.