forked from sageroom/pg_dump-to-s3
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbackup.sh
executable file
·61 lines (53 loc) · 1.85 KB
/
backup.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
#!/bin/bash
set -e
if [ -n "$DEBUG" ]; then
set -x
fi
DB_USER="${DB_USER:-postgres}"
DB_PORT="${DB_PORT:-5432}"
function usage() {
echo "Usage: ./backup.sh"
echo ""
echo "Requires the following environment variables to be set:"
echo " DB_HOST - The hostname or IP address of the database host"
echo " DB_PORT - The port the database can be found on the database host (defaults to 5432)"
echo " DB_NAME - The name of the database to back up"
echo " DB_USER - The user to take the backup with (defaults to postgres)"
echo " DB_PASSWORD - The password to authenticate the user"
echo " S3_HOST - The hostname of the S3 server (ie ams3.digtialoceanspaces.com)"
echo " S3_HOST_BUCKET - The host bucket pattern for resolving a bucket (ie %(bucket)s.ams3.digitaloceanspaces.com)"
echo " S3_REGION - Bucket location region"
echo " BUCKET_NAME - The bucket to store the backup in."
echo " ACCESS_KEY - The S3 access key."
echo " SECRET_KEY - The S3 secret key."
echo ""
}
function validate_variable() {
VAR_NAME=$1
if [ -z "${!VAR_NAME}" ]; then
echo "Environment $VAR_NAME is not set."
usage
exit 1
fi
}
validate_variable "DB_HOST"
validate_variable "DB_PORT"
validate_variable "DB_NAME"
validate_variable "DB_USER"
validate_variable "DB_PASSWORD"
validate_variable "S3_HOST"
validate_variable "S3_HOST_BUCKET"
validate_variable "S3_REGION"
validate_variable "BUCKET_NAME"
validate_variable "ACCESS_KEY"
validate_variable "SECRET_KEY"
echo "Running $DB_NAME backup"
mkdir /tmp/backup
BACKUP_NAME=/tmp/backup/${DB_NAME}-$(date +\%F).sql
export PGPASSWORD=$DB_PASSWORD
pg_dump -U "$DB_USER" -h "$DB_HOST" -p "$DB_PORT" -d "$DB_NAME" > $BACKUP_NAME
s3cmd put $BACKUP_NAME s3://$BUCKET_NAME/ \
--host=$S3_HOST --host-bucket=$S3_HOST_BUCKET --region=$S3_REGION \
--access_key=$ACCESS_KEY \
--secret_key=$SECRET_KEY
echo "Backup complete."