Your Ad Here

Posted By

theroamingcoder on 10/13/10


Tagged

backup ruby amazon s3


Versions (?)

Who likes this?

3 people have marked this snippet as a favorite

kentonnewby
kaks
timpreneur


Website Backup To Amazon S3 Storage


 / Published in: Ruby
 

This handy little script will backup your website\'s database (MySQL) and files and put them into an amazon s3 bucket. You will need to make sure your host has the aws/s3 ruby gem installed. Can easily be extended to include the email folders as well. MAKE SURE TO PLACE IN A NON-WEB-ACCESSIBLE FOLDER! And don\'t forget to schedule the task to run via cron.

  1. #!/usr/bin/ruby
  2. require 'rubygems'
  3. require 'aws/s3'
  4. require 'net/smtp'
  5.  
  6. AWS::S3::Base.establish_connection!(
  7. :access_key_id => 'Your S3 Access Key Goes Here',
  8. :secret_access_key => 'Your S3 Secret Access Key Goes Here'
  9. )
  10.  
  11. $bucket = 'bucket_name_goes_here'
  12. db_host = 'localhost'
  13. db_user = 'database_username'
  14. db_pass = 'database_password'
  15. db_name = 'database_name'
  16. site_dir = '/full/path/to/website/root'
  17. $backup_name = 'example_com_backup'
  18. $notify_on_error = true
  19. $notify_from = 'myself@example.com'
  20. $notify_to = 'myself@example.com'
  21. $notify_port = 25
  22. $notify_server = 'mail.example.com'
  23. $notify_domain = 'example.com'
  24. $notify_user = 'myself+example.com'
  25. $notify_pass = 'emailpassword'
  26. $notify_authtype = :plain
  27.  
  28. def store_file(file)
  29. file_base = File.basename(file)
  30. object_path = $backup_name+"/"+file_base
  31. response = AWS::S3::S3Object.store(object_path, open(file), $bucket)
  32. if response.error? and $notify_on_error
  33. error_email("Failed to store #{file}")
  34. end
  35. end
  36.  
  37. def error_email(message)
  38. #http://www.ruby-doc.org/stdlib/libdoc/net/smtp/rdoc/index.html
  39. Net::SMTP.start($notify_server, $notify_port, $notify_domain, $notify_user, $notify_pass, $notify_authtype) do |smtp|
  40. smtp.open_message_stream($notify_from, [$notify_to]) do |f|
  41. f.puts "From: #{$notify_from}"
  42. f.puts "To: #{$notify_to}"
  43. f.puts 'Subject: Website Backup Script Error'
  44. f.puts message
  45. end
  46. end
  47. end
  48.  
  49. #get database dump
  50. db_file = "#{$backup_name}.sql"
  51. if(system("mysqldump --add-drop-table --user=#{db_user} --password=#{db_pass} --host=#{db_host} #{db_name} > #{db_file}"))
  52. store_file(db_file)
  53. else
  54. error_email("Failed to create #{db_file}")
  55. end
  56. File.delete(db_file)
  57.  
  58. #get filesystem tar.gz
  59. site_file = File.join(Dir.getwd, "#{$backup_name}.tar.gz")
  60. Dir.chdir(site_dir)
  61. if(system("tar -czf #{site_file} *"))
  62. store_file(site_file)
  63. else
  64. error_email("Failed to create #{site_file}")
  65. end
  66. File.delete(site_file)

Report this snippet  

You need to login to post a comment.