in Ruby on Rails

Heroku remote database backup

Heroku’s new toolbelt commands have had a few updates which make copying backups a little trickier. Also, if you want to automate these commands in scheduler, your rake task needs to authenticate before it can run the command.

Here is my rake task to backup the database and copy the backup to another location:

namespace :pgbackup do
desc "Database Backup and copy"
task :db_backup => :environment do

heroku_server = ENV['APP_NAME']
timestamp = Time.now.strftime('%Y%m%d%H%M%S')
temp_path = "latest.dump"

Bundler.with_clean_env do
db_list = `echo "#{ENV['BACKUP_USERNAME']}n#{ENV['BACKUP_PASSWORD']}" | heroku pg:backups capture -a #{heroku_server}`
res = db_list.split("n")[6]
db_id = res.split(" ")[2].strip
restore_url = `heroku pg:backups public-url #{db_id} -a "#{heroku_server}"`
restore_url = URI.extract(restore_url)
restore_url = restore_url[0]
p `curl -o "#{temp_path}" "#{restore_url}"`
end

file = YAML.load_file("#{Rails.root}/config/s3.yml")
config = file[Rails.env]

connection = Fog::Storage.new({
:provider => 'AWS',
:aws_access_key_id => config['access_key_id'],
:aws_secret_access_key => config['secret_access_key'],
:region => 'eu-west-1'
})

directory = connection.directories.get(ENV["APP_NAME"])

file = directory.files.create(:key => "db-backups/#{timestamp}.dump", :body => File.open("#{temp_path}"), :public => false)

end
end

As you can see I have used the fog gem to connect to S3. Fog has other options of where it can connect to so you are not just limited to S3.

You will also have to make sure to add the following environment variables to heroku:

  1. APP_NAME
  2. BACKUP_USERNAME
  3. BACKUP_PASSWORD

The backup username and password are heroku login details for an owner or collaborator account.

Write a Comment

Comment