Skip to content

Instantly share code, notes, and snippets.

@rahuljiresal
Last active February 8, 2016 17:24
Embed
What would you like to do?
Backup MySQL Database to Amazon S3 Bucket
require 'date'
require 'aws/s3'
class Settings
attr_accessor :username, :password, :database, :mysql_location, :access_key, :secret_key, :bucket_name
end
user_settings = Settings.new
user_settings.username = DATABASE_USERNAME
user_settings.password = DATABASE_PASSWORD
user_settings.database = DATABASE_NAME
user_settings.mysql_location = LOCATION_OF_mysqldump_COMMAND
user_settings.access_key = AWS_S3_ACCESS_KEY
user_settings.secret_key = AWS_S3_SECRET_KEY
user_settings.bucket_name = S3_BUCKET_NAME
def mysql_to_s3(settings)
puts "Starting mysql_to_s3 for username: \"" + settings.username + "\"..."
dumpfile = DateTime.now.to_s + ".sql"
command_string = settings.mysql_location + " -u " + settings.username + " -p" + settings.password + " --databases " + settings.database + " > " + dumpfile
status = system command_string
if status
puts "Database backed up."
else
puts "Error in backing up database."
return
end
AWS::S3::Base.establish_connection!(
:access_key_id => settings.access_key,
:secret_access_key => settings.secret_key
)
begin
puts "Looking for bucket..."
bucket = AWS::S3::Bucket.find(settings.bucket_name)
puts "Bucket found."
rescue Exception => e
puts e.message
puts "Error: Bucket " + settings.bucket_name + " might not be present in your Amazon S3 account."
puts "Deleting backup file from local disk..."
File.delete(dumpfile)
return
end
begin
puts "Sending data to Amazon S3..."
response = AWS::S3::S3Object.store(dumpfile, open(dumpfile), settings.bucket_name)
rescue Exception => e
puts "Error: " + e.message
puts "Deleting backup file from local disk..."
File.delete(dumpfile)
return
end
puts "Backup Done."
puts ""
end
mysql_to_s3(user_settings)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment