Search code examples
databaseherokuautomationdatabase-backupspg-restore

Heroku auto restore


I need to implement an automatic trasfer of daily backups from one DB to another DB. Both DB's and apps are hosted on heroku. I know this is possible if to do it manually from local machine with the command:

heroku pgbackups:restore DATABASE `heroku pgbackups:url --app production-app` --app staging-app

But this process should be automated and run not from local machine. I have an idea to write a rake which will execute this command; and run this rake daily with the help of Heroku Scheduler add-on.

Any ideas how it is better to do this? Or maybe there is a better way for this task?

Thanks in advance.


Solution

  • I managed to solve the issue myself. It appeared to be not so complex. Here is the solution, maybe it'll be useful to somebody else: 1. I wrote a script which copies the latest dump from a certain server to the DB of the current server

    namespace :backup do
      desc "copy the latest dump from a certain server to the DB of the current server"
      task restore_last_write_dump: :environment do
        last_dump_url = %x(heroku pgbackups:url --app [source_app_name])
        system("heroku pgbackups:restore [DB_to_target_app] '#{last_dump_url}' -a [target_app_name] --confirm [target_app_name]")
        puts "Restored dump: #{last_dump_url}"
      end
    
    end
    
    1. To avoid authenication upon each request to the servers, craete a file .netrc in the app root (see details here https://devcenter.heroku.com/articles/authentication#usage-examples)

    2. Setup Scheduler add-on for heroku and add our rake task along with the frequency of its running.

    That is all.