Last active
January 12, 2019 02:41
-
-
Save edmangimelli/f41fb3e779fa0ccb1316f0e506bc7e45 to your computer and use it in GitHub Desktop.
rails rake task for backing up heroku database to s3 bucket
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
# this gist was inspired by hopsoft's | |
# https://gist.github.com/hopsoft/56ba6f55fe48ad7f8b90 | |
# and a snippet given to me by mckbeardy on Midwest Dev Chat (Zach Mckenzie) | |
# put this file in lib/tasks | |
# your_rails_project/lib/tasks/backup_db_to_s3.rake (or whatever you want to name it) | |
# | |
# usage: | |
# | |
# rails db:backup_to_s3 | |
# or | |
# rake db:backup_to_s3 | |
# | |
# personally, i made a task with heroku scheduler to automatically backup the db in the | |
# middle of the night | |
# | |
# feel free to ask any questions. | |
require 'aws-sdk' | |
namespace :db do | |
task :backup_to_s3 => :environment do | |
file_name = (->{ | |
time = Time.now | |
host = ENV['HOST'] | |
host = host.instance_of?(String) ? host.split('.')[0] : nil | |
[ | |
'DB backup', | |
host, | |
time.strftime("%Y-%m-%d"), | |
time.strftime("%H.%M.%S.%L_%Z") | |
].compact.join('__') + '.dump' | |
}).call | |
file_name_with_full_path = "#{Rails.root}/db/#{file_name}" | |
app = Rails.application.class.parent_name.underscore | |
host, db, user, password = (->{ | |
config = ActiveRecord::Base.connection_config | |
[:host, :database, :username, :password].map{|k| config[k]} | |
}).call | |
run("echo #{host}:5432:#{db}:#{user}:#{password} > ~/.pgpass") | |
run([ | |
'pg_dump', | |
"--host #{host}", | |
"--username #{user}", | |
'--verbose', | |
'--clean', | |
'--no-owner', | |
'--no-acl', | |
'--format=c', | |
"--dbname #{db}", | |
'--no-password', | |
"> #{file_name_with_full_path}" | |
].join(' ')) | |
s3 = Aws::S3::Resource.new(region: ENV['AWS_REGION']) | |
obj = s3.bucket(ENV['S3_BUCKET_NAME']).object(file_name) | |
puts "Uploading file #{file_name}" | |
obj.upload_file(file_name_with_full_path) | |
puts "Done" | |
end | |
private | |
def run(str) | |
puts str | |
system str | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment