Skip to content

Instantly share code, notes, and snippets.

@FUT
Last active August 29, 2015 14:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save FUT/da6b0fcf450647f8f146 to your computer and use it in GitHub Desktop.
Save FUT/da6b0fcf450647f8f146 to your computer and use it in GitHub Desktop.
Capistrano MySQL backup task
namespace :mysql do
desc "Performs a backup (using mysqldump) in app shared dir"
task :backup, :roles => :db, :only => { :primary => true } do
if rails_env != 'production'
puts 'Backup will be performed for production environment only! Exiting.'
else
keep_backups = 15
filename = "#{application}.#{rails_env}.db_backup.#{Time.now.strftime '%d.%m.%Y_%H-%M'}.sql"
backups = "#{shared_path}/backups"
filepath = "#{backups}/#{filename}"
text = capture "cat #{deploy_to}/current/config/database.yml"
yaml = YAML::load(text)['production']
count = capture("ls #{backups}/ | wc -l").to_i
run "rm -rf `ls #{backups}/ | head -n 1`" if count > keep_backups
on_rollback { run "rm #{filepath}" }
run "mysqldump -u#{yaml['username']} -p#{yaml['password']} -h #{yaml['host']} #{yaml['database']} > #{filepath}"
end
end
end
before 'deploy:update_code', 'mysql:backup'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment