-
Notifications
You must be signed in to change notification settings - Fork 58
/
backup.sh
executable file
·65 lines (50 loc) · 1.67 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
62
63
64
65
#!/bin/bash
set -o errexit -o nounset -o pipefail
export AWS_PAGER=""
s3() {
aws s3 --region "$AWS_REGION" "$@"
}
s3api() {
aws s3api "$1" --region "$AWS_REGION" --bucket "$S3_BUCKET_NAME" "${@:2}"
}
bucket_exists() {
s3 ls "$S3_BUCKET_NAME" &> /dev/null
}
create_bucket() {
echo "Bucket $S3_BUCKET_NAME doesn't exist. Creating it now..."
# create bucket
s3api create-bucket \
--create-bucket-configuration LocationConstraint="$AWS_REGION" \
--object-ownership BucketOwnerEnforced
# block public access
s3api put-public-access-block \
--public-access-block-configuration \
"BlockPublicAcls=true,IgnorePublicAcls=true,BlockPublicPolicy=true,RestrictPublicBuckets=true"
# enable versioning for objects in the bucket
s3api put-bucket-versioning --versioning-configuration Status=Enabled
# encrypt objects in the bucket
s3api put-bucket-encryption \
--server-side-encryption-configuration \
'{"Rules": [{"ApplyServerSideEncryptionByDefault": {"SSEAlgorithm": "AES256"}}]}'
}
ensure_bucket_exists() {
if bucket_exists; then
return
fi
create_bucket
}
pg_dump_database() {
pg_dump --no-owner --no-privileges --clean --if-exists --quote-all-identifiers "$DATABASE_URL"
}
upload_to_bucket() {
# if the zipped backup file is larger than 50 GB add the --expected-size option
# see https://docs.aws.amazon.com/cli/latest/reference/s3/cp.html
s3 cp - "s3://$S3_BUCKET_NAME/$(date +%Y/%m/%d/backup-%H-%M-%S.sql.gz)"
}
main() {
ensure_bucket_exists
echo "Taking backup and uploading it to S3..."
pg_dump_database | gzip | upload_to_bucket
echo "Done."
}
main