Created
December 1, 2021 06:09
This file contains 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 | |
# Takes a full backup of the database and stores it in the backup folder | |
# Run this script as the postgres user | |
DATE=`date +%Y-%M-%d-%H-%M-%S` | |
logged_in_user=$USER | |
FILE=snapshot_$DATE.tar | |
start=`date +%s` | |
PG_PASSWORD='' | |
PG_HOSTNAME='' | |
PG_USERNAME='' | |
PG_PORT='5432' | |
PRIMARY_DB='' | |
BACKUP_DB='' | |
BACKUP_PG_PASSWORD='' | |
BACKUP_PG_HOSTNAME='' | |
BACKUP_PG_USERNAME='' | |
BACKUP_PG_PORT='5432' | |
exec 3<> /logs/sync_logs_$DATE.log | |
SDIR="/home/$logged_in_user/aws/snapshot" | |
if [ -d "$SDIR" ]; then | |
echo "Snapshot Directory already present" >&3 | |
else | |
echo "Initiating a new snapshot directory $SDIR" >&3 | |
mkdir -p /home/$logged_in_user/aws/snapshot | |
fi | |
SLDIR="/home/$logged_in_user/aws/logs/snapshot_logs" | |
if [ -d "$SLDIR" ]; then | |
echo "Snapshot logs dir already present" >&3 | |
else | |
echo "Initiating a new snapshot logs directory $SLDIR" >&3 | |
mkdir -p /home/$logged_in_user/aws/logs/snapshot_logs | |
fi | |
echo 'Initiating Backup' >&3 | |
conn=`pg_isready -d $PRIMARY_DB -h $PG_HOSTNAME -p $PG_PORT -U $PG_USERNAME` | |
if [[ $conn =~ "accepting" ]]; then | |
echo "Connection Successful !" >&3 | |
else | |
echo "Handshake Unsuccessful !" >&3 | |
exit 1 | |
fi | |
if [ -f "$FILE" ]; then | |
echo "$FILE exists." >&3 | |
else | |
echo "$FILE does not exist." >&3 | |
echo "Creating a new snapshot" >&3 | |
echo `PGPASSWORD=$PG_PASSWORD pg_dump -v -h $PG_HOSTNAME -U $PG_USERNAME -F t $PRIMARY_DB > $SDIR/snapshot_$DATE.tar` >&3 | |
echo `date` - Backup complete >&3 | |
fi | |
echo `date` - Restoration Started >&3 | |
echo '' | |
echo -e `PGPASSWORD=$BACKUP_PG_PASSWORD pg_restore -d $BACKUP_DB $SDIR/snapshot_$DATE.tar -c -v -U $BACKUP_PG_USERNAME -h $BACKUP_PG_HOSTNAME` >&3 | |
end=`date +%s` | |
runtime=$( echo "$end - $start" | bc -l ) | |
echo `date` - DB Restoration Completed in- $runtime Seconds >&3 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment