Created
February 20, 2016 13:57
-
-
Save blaze182/bc33c892cfd3f6abc6d3 to your computer and use it in GitHub Desktop.
Capistrano 3 PostgreSQL backup task for Rails
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# ... | |
# 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 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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