Skip to content

Instantly share code, notes, and snippets.

@eekfonky
Created October 30, 2017 15:12
Show Gist options
  • Save eekfonky/8a1082ec04f6623d2e5512c9de8777a9 to your computer and use it in GitHub Desktop.
Save eekfonky/8a1082ec04f6623d2e5512c9de8777a9 to your computer and use it in GitHub Desktop.
Backup a Mongo database to S3
#!/bin/bash
clear
# Check AWS credentials
if [[ $(aws configure list | grep "*") && $? -eq 0 ]]; then
:
else
echo -e "\\n\\e[1mPlease configure AWS credentials to continue...\\e[0m"
aws configure
fi
# Force file syncronization and lock writes
echo -e "\\n\\e[31mLock Database writes...\\e[0m"
mongo admin --eval "printjson(db.fsyncLock())"
# Variables
BACKUPDIR="/home/$USER/backup"
TIMESTAMP=$(date +%F-%H.%M)
S3_BUCKET_NAME="s3://<BUCKET_NAME>"
# Create backup
echo -e "\\n\\e[1mTaking database dump and storing in /home/$USER/backup/...\\e[0m"
# check for backup directory
if [[ ! -d "$BACKUPDIR" ]]; then
mkdir -p "$BACKUPDIR"
fi
cd "$BACKUPDIR" || exit 1
mongodump -o "$BACKUPDIR"/mongodb-"$TIMESTAMP"
tar -C "$BACKUPDIR" -czf mongodb-"$TIMESTAMP".tar.gz mongodb-"$TIMESTAMP"
# Upload to S3
echo -e "\\n\\e[1mUploading dump to S3...\\e[0m"
aws s3 cp mongodb-"$TIMESTAMP".tar.gz "$S3_BUCKET_NAME"
# Unlock database writes
echo -e "\\n\\e[32mUnlock Database writes...\\e[0m"
mongo admin --eval "printjson(db.fsyncUnlock())"
# Delete the backup after sync to S3
echo -e "\\n\\e[1mRemoving local backups...\\e[0m"
sudo rm -rf "${BACKUPDIR:?}"/*.tar.gz
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment