Skip to content

Instantly share code, notes, and snippets.

@blaze182
Created February 20, 2016 13:57
Show Gist options
  • Save blaze182/bc33c892cfd3f6abc6d3 to your computer and use it in GitHub Desktop.
Save blaze182/bc33c892cfd3f6abc6d3 to your computer and use it in GitHub Desktop.
Capistrano 3 PostgreSQL backup task for Rails
# ...
# config/deploy.rb, config/deploy/production.rb etc.
# contents omitted
###
# example: add backup task prior to deploy
namespace :deploy do
before :deploy, "db:dump"
end
# The task assumes you have figaro application.yml config in Capistrano shared folder
# https://github.com/laserlemon/figaro
require 'sshkit'
namespace :db do
desc "Backup your PostgreSQL database to ~/"
task :dump do
on roles(:db) do
@dbconf = dbconfig
dbuser = @dbconf['username']
dbname = @dbconf['database']
dbhost = @dbconf['host']
# feel free to add required flags for pg_dump
# http://www.postgresql.org/docs/9.4/static/app-pgdump.html
within '~/' do
execute :pg_dump,
"-W -U #{dbuser} -h #{dbhost} --format=plain --quote-all-identifiers",
"#{dbname} > \"pims_backup_$(date +%F_%R).sql\"",
interaction_handler: {
'Password: ' => "#{dbpass}\n"
}
end
end
end
# extract Rails database config
def dbconfig
YAML::load(
capture :cat, "#{current_path}/config/database.yml"
)[fetch(:rails_env)]
end
# extract password from figaro shared config file
def dbpass
YAML::load(
capture :cat, "#{shared_path}/config/application.yml"
)['DATABASE_PASSWORD']
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment