Skip to content

Instantly share code, notes, and snippets.

@akash-gajjar
Last active June 22, 2023 12:42
Show Gist options
  • Save akash-gajjar/c75f8bcf3de602028943bc366a47a587 to your computer and use it in GitHub Desktop.
Save akash-gajjar/c75f8bcf3de602028943bc366a47a587 to your computer and use it in GitHub Desktop.
A script to perform backup and restore operations for a MongoDB database.
#!/bin/bash
# Script: backup-restore.sh
# Description: A script to perform backup and restore operations for a MongoDB database.
# Author: Aakash Gajjar
# Last modified: 2023-06-03
# S3 bucket to upload database backup file
bucketName=""
# Database connection credentials
dbUser=""
dbPassword=""
# Database dump directory
dumpDir="sky-dump"
# Usage function to display script usage information
usage() {
echo "Usage: ./backup-restore.sh [OPTIONS] [ARGUMENTS]"
echo "Description: Perform backup and restore operations for a MongoDB database."
echo ""
echo "Options:"
echo " -h, --help Display this help message."
echo " -v, --version Display script version."
echo ""
echo "Arguments:"
echo " backup Perform a database backup."
echo " restore <S3Uri> Restore a database from the specified s3 backup file."
echo ""
echo "Examples:"
echo " ./backup-restore.sh backup"
echo " ./backup-restore.sh restore s3://bucket/backup-2023-01-01.tar"
echo ""
}
# Version function to display script version information
version() {
echo "backup-restore.sh version 1.0"
echo "Last modified: 2023-02-11"
}
# if error stop executing early
set -e
function backup() {
name="dev-primary"
timestamp=`/bin/date +%Y-%m-%d-%H-%M-%S`
DEST="$name-backup-$timestamp.tar"
echo "[1/4] Dumping databases ...\n"
mongodump -v --port=27017 --authenticationDatabase="admin" -u="$dbUser" -p="$dbPassword" --gzip --out="dumpDir"
echo "[2/4] Compressing files ...\n"
tar cvf $DEST "./$dumpDir" && rm -rf "./$dumpDir"
echo "[3/4] Uploading files to S3 bucket\n"
aws s3 cp $DEST "s3://$bucketName"
echo "[4/4] Cleaning local files\n"
rm -rf $DEST
}
function restore() {
filename=$(basename $1)
echo "[1/4] Downloading $1 to $filename"
# aws s3 cp $1 $filename
echo "[2/4] Extracting files to dump"
tar xvf $filename "./$dumpDir"
echo "[3/4] Restoring database"
mongorestore -v --port=27017 --authenticationDatabase="admin" -u="$dbUser" -p="$dbPassword" --drop --preserveUUID --gzip "./$dumpDir"
echo "[4/4] Cleaning local files\n"
rm $filename
}
# Check the number of command-line arguments
if [[ $# -eq 0 ]]; then
echo "Error: No arguments provided."
usage
exit 1
fi
# Process the command-line arguments
case "$1" in
-h | --help)
usage
;;
-v | --version)
version
;;
backup)
backup
;;
restore)
if [[ $# -ne 2 ]]; then
echo "Error: Missing backup file argument."
usage
exit 1
fi
restore "$2"
;;
*)
echo "Error: Invalid argument: $1"
usage
exit 1
;;
esac
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment