Carl Hörberg on development

I didn't find any good solutions on how to automatically backup the Heroku database to S3, but with some inspiration from this blog post I cooked up a solution which takes advantage of the PG Backups and Cron addons on Heroku to backup to S3 daily, for free.

require 'aws/s3'
require 'heroku'
require 'heroku/command'
require 'heroku/command/auth'
require 'heroku/command/pgbackups'

task :cron do
  class Heroku::Auth
    def self.client
      Heroku::Client.new ENV['heroku_login'], ENV['heroku_passwd']
    end
  end

  Heroku::Command.run 'pgbackups:capture', ['--expire', '--app', ENV['heroku_appname']]
  url = capture_stdout do
    Heroku::Command.run 'pgbackups:url', ['--app', 'dmks']
  end

  AWS::S3::Base.establish_connection!(:access_key_id => ENV['s3_access_key'], :secret_access_key => ENV['s3_secret_key'])
  AWS::S3::S3Object.store "pgdb-#{Time.now.strftime('%y%m%d_%H%M')}.dump", open(url), ENV['s3_backup_bucket']
end

module Kernel
  def capture_stdout
    out = StringIO.new
    $stdout = out
    yield
    return out.string
  ensure
    $stdout = STDOUT
  end
end

view raw Rakefile.rb This Gist brought to you by GitHub.

I hade to monkey patch Heroku::Auth so it doesn't ask for login/password from the prompt, and I had to add a 'capture_stdout' to Kernel to be able to get the url I then download and upload to S3.

Update: As Will Leinweber mentioned in the comments, Heroku are about to offer this functionallity, but to date this feature is still in private beta.

 
blog comments powered by Disqus