Skip to content

Instantly share code, notes, and snippets.

@qweluke
Created February 20, 2018 14:19
Show Gist options
  • Save qweluke/2589e0b902805292e2a746ea37789f3e to your computer and use it in GitHub Desktop.
Save qweluke/2589e0b902805292e2a746ea37789f3e to your computer and use it in GitHub Desktop.
capifony - dump database and purge old dumps
set :keep_db_backups, 5
set :backup_path, "db_dumps"
set :backup_name, "database"
task :dump_db do
# read symfony configuration from remote server
params = capture "cat #{deploy_to}/current/app/config/parameters.yml"
config = YAML.load(params)
backup_to = "#{fetch(:deploy_to)}/#{fetch(:backup_path)}"
run "mkdir -p #{backup_to}"
db_user = config['parameters']['database_user']
db_pw = config['parameters']['database_password']
db_name = config['parameters']['database_name']
# generate filename
filename = "#{fetch(:backup_name)}_#{default_stage}_#{db_name}_#{Time.now.strftime '%Y-%m-%d_%H:%M:%S'}.sql.bz2"
run "mysqldump -u #{db_user} -p#{db_pw} #{db_name} | bzip2 -9 > #{backup_to}/#{filename}"
end
task :purge_old_dumps do
max_keep = fetch(:keep_db_backups, 5).to_i
backup_to = "#{fetch(:deploy_to)}/#{fetch(:backup_path)}"
backup_files = capture("ls -t #{backup_to}/#{fetch(:backup_name)}*").split.reverse
if max_keep >= backup_files.length
info "No old database backups to clean up"
else
p "Keeping #{max_keep} of #{backup_files.length} database backups"
delete_backups = (backup_files - backup_files.last(max_keep)).join(" ")
run "rm -rf #{delete_backups}"
end
end
# example usage
before "symfony:cache:warmup", "dump_db"
before "symfony:cache:warmup", "symfony:doctrine:migrations:migrate"
before "symfony:cache:warmup", "purge_old_dumps"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment