forked from gabfl/pg_dump-to-s3
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpg_dump-to-s3.sh
executable file
·74 lines (56 loc) · 1.95 KB
/
pg_dump-to-s3.sh
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
#!/bin/bash
# _ _ _____
# _ __ __ _ __| |_ _ _ __ ___ _ __ | |_ ___ ___|___ /
# | '_ \ / _` | / _` | | | | '_ ` _ \| '_ \ _____| __/ _ \ _____/ __| |_ \
# | |_) | (_| | | (_| | |_| | | | | | | |_) |_____| || (_) |_____\__ \___) |
# | .__/ \__, |___\__,_|\__,_|_| |_| |_| .__/ \__\___/ |___/____/
# |_| |___/_____| |_|
#
# Project at https://github.com/gabfl/pg_dump-to-s3
#
set -e
# Set current directory
DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
# Import config file
source $DIR/pg_dump-to-s3.conf
# Vars
NOW=$(date +"%Y-%m-%d-at-%H-%M-%S")
DELETETION_TIMESTAMP=`[ "$(uname)" = Linux ] && date +%s --date="-$DELETE_AFTER"` # Maximum date (will delete all files older than this date)
# Split databases
IFS=',' read -ra DBS <<< "$PG_DATABASES"
# Delete old files
echo " * Backup in progress.,.";
# Loop thru databases
for db in "${DBS[@]}"; do
FILENAME="$NOW"_"$db"
echo " -> backing up $db..."
# Dump database
pg_dump -Fc -h $PG_HOST -U $PG_USER -p $PG_PORT $db > /tmp/"$FILENAME".dump
# Copy to S3
aws s3 cp /tmp/"$FILENAME".dump s3://$S3_PATH/"$FILENAME".dump --storage-class STANDARD_IA
# Delete local file
rm /tmp/"$FILENAME".dump
# Log
echo " ...database $db has been backed up"
done
# Delere old files
echo " * Deleting old backups...";
# Loop thru files
aws s3 ls s3://$S3_PATH/ | while read -r line; do
# Get file creation date
createDate=`echo $line|awk {'print $1" "$2'}`
createDate=`date -d"$createDate" +%s`
if [[ $createDate -lt $DELETETION_TIMESTAMP ]]
then
# Get file name
FILENAME=`echo $line|awk {'print $4'}`
if [[ $FILENAME != "" ]]
then
echo " -> Deleting $FILENAME"
aws s3 rm s3://$S3_PATH/$FILENAME
fi
fi
done;
echo ""
echo "...done!";
echo ""