Skip to content

Instantly share code, notes, and snippets.

@xarimanx
Created January 16, 2015 15:59
Show Gist options
  • Save xarimanx/91df1f37929b87d48de1 to your computer and use it in GitHub Desktop.
Save xarimanx/91df1f37929b87d48de1 to your computer and use it in GitHub Desktop.
Backup project database. Options: DIR=backups RAILS_ENV=production MAX=7
# encoding: utf-8
namespace :db do desc "Backup project database. Options: DIR=backups RAILS_ENV=production MAX=7"
task :backup => [:environment] do
datestamp = Time.now.strftime("%Y-%m-%d_%H-%M-%S")
base_path = Rails.root
base_path = File.join(base_path, ENV['DIR'] || "backups")
backup_base = File.join(base_path, 'db_backups')
file_name = "#{datestamp}_#{Rails.env}_dump.sql"
backup_file = File.join(backup_base, file_name)
FileUtils.mkdir_p(backup_base)
db_config = ActiveRecord::Base.configurations[Rails.env]
`mysqldump -u #{db_config['username']} -p#{db_config['password']} -i -c -q #{db_config['database']} > #{backup_file}`
raise "Unable to make DB backup!" if ( $?.to_i > 0 )
`gzip -9 #{backup_file}`
dir = Dir.new(backup_base)
all_backups = dir.entries.sort[2..-1].reverse
puts "Created backup: #{backup_file}"
max_backups = (ENV["MAX"].to_i if ENV["MAX"].to_i > 0) || 30
unwanted_backups = all_backups[max_backups..-1] || []
file_name = "#{file_name}.gz"
AWS.config(access_key_id: ACCESS_KEY_ID,
secret_access_key: SECRET_ACCESS_KEY )
s3 = AWS::S3.new
folder = "db_backups/#{file_name}"
s3.buckets[BACKUPS_BUCKET_NAME].objects[folder].write(File.open(File.join(backup_base, file_name), 'rb'))
for unwanted_backup in unwanted_backups
FileUtils.rm_rf(File.join(backup_base, unwanted_backup))
s3.buckets[BACKUPS_BUCKET_NAME].objects["#{base_path}/#{unwanted_backup}"].delete
end
puts "Deleted #{unwanted_backups.length} backups, #{all_backups.length - unwanted_backups.length} backups available"
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment