Backup heroku database and saved on AWS s3

Add gem "fog"

Create rake file lib/tasks/db.rake

namespace :db do
  desc "Backs up heroku database and saved on AWS s3."
  task import_from_heroku: [ :environment, :create ] do
    HEROKU_APP_NAME = 'appname' # Change this if app name is not picked up by `heroku` git remote.
    dump_filename = "appname_prod_#{Time.now.strftime('%d-%m-%Y')}"
    c = Rails.configuration.database_configuration[Rails.env]
    heroku_app_flag = HEROKU_APP_NAME ? " --app #{HEROKU_APP_NAME}" : nil
    Bundler.with_clean_env do
      puts "[1/4] Capturing backup on Heroku"
      `heroku pg:backups capture DATABASE_URL#{heroku_app_flag}`
      puts "[2/4] Downloading backup onto disk"
      `curl -o tmp/#{dump_filename}.dump \`heroku pg:backups public-url #{heroku_app_flag} | cat\``
      puts "[3/4] Mounting backup on local database"
      # `pg_restore --clean --verbose --no-acl --no-owner -h localhost -d #{c["database"]} tmp/#{dump_filename}.dump`
 

      require 'fog'
      puts "Seting AWS S3 credentials"
      credentials = {
        aws_access_key_id: ENV.fetch('AWS_ACCESS_KEY_ID'),
        aws_secret_access_key: ENV.fetch('AWS_SECRET_ACCESS_KEY'),
        region: ENV.fetch('AWS_REGION')
      }

      puts "Initialiing AWS Client"
      client = Fog::Storage::AWS.new(credentials)

      puts "Uploading file"
      `curl -v --upload-file tmp/#{dump_filename}.dump --url https://bucketname.s3.amazonaws.com/#{dump_filename}.dump`
      puts "[4/4] Removing local backup"
      `rm tmp/#{dump_filename}.dump`
      puts "Done."

    end
  end
end


#Run rake task:

rake db:import_from_heroku

Comments

  1. Nice information thanks for sharing this with us
    Visit chloros technology

    ReplyDelete
  2. Thanks for sharing code for website development this is really useful if we want detail information then Software And Web Developer will help you.

    ReplyDelete
  3. Your blog is in a convincing manner, thanks for sharing such an information with lots of your effort and time
    ruby on rails training India
    ruby on rails training Hyderabad

    ReplyDelete

Post a Comment

Popular Posts

How to pass hash in Postman

nginx: unrecognized service

Bootstrap Select Picker append add new item if search not exist

Reading Excel Sheets using "Roo" gem in ruby on rails

Add CORS to Nginx on AWS Elastic Beanstalk

Enable gzip compression on Elastic Beanstalk with nginx

Can't connect to local MySQL server through socket '/var/run/mysqld/mysqld.sock'

Get video duration by URL in Ruby on Rails

site-enables nginx setting in ruby in rails