Backup to S3

This is a small ruby script that you should symbolically link to from your cron.daily directory. It does the following:

The script creates backups for each day of the last week and also has monthly permanent backups.

To use this script, you must:

bk

#!/bin/env ruby
 
require 'rubygems'
require 'aws/s3'
 
# Create a tar file with the wiki data files.
wiki_data = '/path/to/wiki/data'
target_dirs = ['attic', 'media', 'meta', 'pages']
tar_dirs = ''
target_dirs.each do |dir| 
  tar_dirs += wiki_data + '/' + dir + ' '
end
weekday = Time.now.wday
backup_filename = "/path/to/backup/wiki-#{weekday}.tar"
`tar -cvf #{backup_filename} #{tar_dirs}`
`gzip #{backup_filename}`
backup_filename += '.gz'
 
# If we are on monthly anniversary, archive a permanent backup.
permanent_backup = nil
if Time.now.day == 1   # Hardwired but what the hey...
  timestamp = Time.now.strftime("%Y-%m-%d")
  permanent_backup = "wiki-#{timestamp}.tar.gz"
end
 
# Put the backup file in the S3 bucket under backups.
 
AWS::S3::Base.establish_connection!(
  :access_key_id         => '...put your access key here...',
  :secret_access_key     => '...put your secret access key here...'
)
bucket_name = '...put your bucket name for wiki backups here...'
begin
  AWS::S3::Bucket.find( bucket_name )
  AWS::S3::S3Object.store(
    File.basename(backup_filename),
    open(backup_filename),
    bucket_name
  )
  puts "#{backup_filename} was successfully backed up to Amazon S3"
  if permanent_backup
    AWS::S3::S3Object.store(
      permanent_backup,
      open(backup_filename),
      bucket_name
    )
    puts "#{permanent_backup} (monthly archive) was successfully backed up to Amazon S3"
  end
 
rescue
  puts "Unable to backup file to S3"
end