Skip to content

Instantly share code, notes, and snippets.

@bmaland
Created May 14, 2009 18:23
Show Gist options
  • Select an option

  • Save bmaland/111804 to your computer and use it in GitHub Desktop.

Select an option

Save bmaland/111804 to your computer and use it in GitHub Desktop.
Backup script for Heroku db's - created for crantastic.org
#!/usr/bin/zsh
# -*- Abstract -*-
# Backup the database from your Heroku webapp. 7 day rotating daily backup,
# stores a weekly copy every week (on sundays).
#
# The latest version of this script is available from http://gist.github.com/111804
# Code by Bjørn Arild Mæland [github.com/Chrononaut]
#
# -*- Requirements and usage -*-
# Requires bzip2, and heroku, taps and sqlite3 ruby gems. ZSH might be a dependency -
# the script is untested in bash, etc. Remember to set up heroku user credentials.
# Also make sure that this script is executable (+x) before adding the crontab entry.
#
# Sample crontab:
# 01 00 * * * /home/$USER/backup/heroku-db-backup.sh
# Make sure we have a somewhat reasonable PATH
PATH="/opt/ruby-enterprise/bin:/bin:/usr/bin:/usr/local/bin:$PATH"
# Configuration
APP=crantastic
BACKUP_ROOT=$HOME/backup/$APP
# End of user configuration - you shouldn't need to modify below this point
TARGET=$BACKUP_ROOT/`date +%m-%d-%Y`.sqlite3
WTARGET=$BACKUP_ROOT/weekly/`date +%V-%Y`.sqlite3.bz2
# creates dir if it doesn't already exist
create_if_missing() {
if [[ ! -d $1 ]]; then mkdir -p $1 || exit 1; fi
}
create_if_missing $BACKUP_ROOT
create_if_missing $BACKUP_ROOT/weekly
cd $BACKUP_ROOT
if [[ ! -f $TARGET.bz2 ]]; then
heroku db:pull sqlite://$TARGET --app $APP || exit 1
bzip2 $TARGET || exit 1
fi
# Create a new weekly every Sunday
if [[ (! -f $WTARGET) && (`date +%u` -eq 7) ]]; then
mv `ls *.bz2 -r|head -1` $WTARGET || exit 1 # New weekly backup - move newest file
fi
# Cleanup old files - only keep a week of dailies
if ls | grep bz2 > /dev/null; then # silly check for empty dir
while [[ `ls *.bz2 |wc -l` -gt 7 ]]; do rm `ls *.bz2 -tr|head -1`; done
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment