Skip to content

Instantly share code, notes, and snippets.

@quangthe
Created March 11, 2020 03:16
Show Gist options
  • Save quangthe/ed087111fa1effc082c6f1bf88d69923 to your computer and use it in GitHub Desktop.
Save quangthe/ed087111fa1effc082c6f1bf88d69923 to your computer and use it in GitHub Desktop.
Backup tienluong-db to S3
#! /usr/bin/python
import boto3
import subprocess
import datetime
import os
now = datetime.datetime.now()
bucket = "dtcorpbackup"
filename = "dump_{}-{:0>2}-{:0>2}_{:0>2}:{:0>2}:{:0>2}.sql".format(now.year, now.month, now.day, now.hour, now.minute, now.second)
path = "/tmp/" + filename
print "Dumping DB to file {}".format(path)
backup_process = subprocess.Popen(
"docker exec -t tienluong-db pg_dumpall -c -U postgres > {}".format(path),
stdout=subprocess.PIPE,
shell=True)
(output, error) = backup_process.communicate()
if error is not None:
print error
# Let's use Amazon S3
s3 = boto3.resource('s3')
# Upload a new file
print "Uploading {} to bucket {}".format(filename, bucket)
data = open(path, 'rb')
s3.Bucket(bucket).put_object(Key=filename, Body=data)
print "Uploaded {} to bucket".format(filename, bucket)
os.remove(path)
print "Remove file {}".format(path)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment