Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
rails rake task for backing up heroku database to s3 bucket
# 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