Created
January 11, 2023 16:00
-
-
Save shahidcodes/47527f33dec05361f33b5e3b1527fc77 to your computer and use it in GitHub Desktop.
Bash script to create mongodb backup and upload to s3
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/bash | |
ADMIN_DB_URI="mongodb://backupuser:backupuser@localhost:27017/admin?authSource=admin" | |
MONGODUMP_PATH="/usr/bin/mongodump" | |
S3_BUCKET_NAME="dbbackups" #replace with your bucket name on Amazon S3 | |
S3_BUCKET_PATH="backups" | |
#Force file syncronization and lock writes | |
mongosh $ADMIN_DB_URI --eval "printjson(db.fsyncLock())" | |
# defind the database names | |
declare -a arr=("db1" "db2" "db3" "db4") | |
## now loop through the above array | |
for MONGO_DATABASE in "${arr[@]}" | |
do | |
echo $MONGO_DATABASE | |
# construct database uri for above db | |
DATABASE_URI="mongodb://backupuser:backupuser@localhost:27017/$MONGO_DATABASE?authSource=admin" | |
echo $MONGODUMP_PATH | |
TIMESTAMP=`date +%F-%H%M` | |
TMP_PATH=$MONGO_DATABASE-$TIMESTAMP | |
TMP_PATH_FILE=$MONGO_DATABASE-$TIMESTAMP.tar | |
# Create backup | |
$MONGODUMP_PATH --quiet -d $MONGO_DATABASE $DATABASE_URI | |
# move dump folder to a path | |
mv dump $TMP_PATH | |
tar cf $TMP_PATH_FILE $TMP_PATH | |
# Upload to S3 | |
s3cmd put $TMP_PATH_FILE s3://$S3_BUCKET_NAME/$S3_BUCKET_PATH/$TMP_PATH_FILE | |
# Unlock database writes | |
mongo $ADMIN_DB_URI --eval "printjson(db.fsyncUnlock())" | |
# Delete local files | |
rm -rf $MONGO_DATABASE-* | |
done |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment