Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
Automating MongoDB dump using cron job and saving on s3 using s3cmd
#!/bin/bash
#Force file syncronization and lock writes
mongo admin --eval "printjson(db.fsyncLock())"
MONGODUMP_PATH="/usr/bin/mongodump"
MONGO_HOST="server_ip" #replace with your server ip
MONGO_PORT="27017"
USER_NAME="myDB"
PASSWORD="password"
MONGO_DATABASE="m_DB_test" #replace with your database name
TIMESTAMP=`date +%F-%H%M`
S3_BUCKET_NAME="Backup-bucket" #replace with your bucket name on Amazon S3
S3_BUCKET_PATH="" // path to bucket in s3
# Create backup
$MONGODUMP_PATH -h $MONGO_HOST:$MONGO_PORT -d $MONGO_DATABASE -u $USER_NAME -p $PASSWORD
#Unlock database writes
mongo admin --eval "printjson(db.fsyncUnlock())"
# Add timestamp to backup
mv dump mongodb-$HOSTNAME-$TIMESTAMP
tar cf mongodb-$HOSTNAME-$TIMESTAMP.tar mongodb-$HOSTNAME-$TIMESTAMP
# Upload to S3
echo "Now pushing to S3"
/usr/local/bin/s3cmd put mongodb-$HOSTNAME-$TIMESTAMP.tar s3://$S3_BUCKET_NAME/$S3_BUCKET_PATH/mongodb-$HOSTNAME-$TIMESTAMP.tar
#Delete dump from this VPS
/bin/rm -r mongodb-$HOSTNAME-*
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment