DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Snippets has posted 5883 posts at DZone. View Full User Profile

Upload_to_s3 - Ruby S3 Upload Client

06.01.2007
| 10200 views |
  • submit to reddit
        Prerequisites:
gem install aws-s3
gem install main

#!/bin/env ruby

require 'rubygems'
require 'main'
require 'aws/s3'
include AWS::S3

Main {
  argument('source_filename') {
    cast :string
    description 'source filename to copy to S3'
  }

  argument('bucket_name') {
    cast :string
    description 'bucket to place the file in on S3'
  }

  option('access_key_id') {
    argument :optional
    description 'specify the access_key_id manually'
    default 'put your access key here if you want'
  }

  option('secret_access_key') {
    argument :optional
    description 'specify the secret key manually'
    default 'put your secret key here if you want'
  }

  def run
    bucket_name = params['bucket_name'].value
    source_filename = params['source_filename'].value

    Base.establish_connection!(
      :access_key_id     => params['access_key_id'].value,
      :secret_access_key => params['secret_access_key'].value
    )

    begin
      Bucket.find(bucket_name)
    rescue
      puts "Need to make bucket #{bucket_name}.."
      Bucket.create(bucket_name)

      # Confirm its existence..
      Bucket.find(bucket_name)
    end

    puts "Got bucket.."
    puts "Uploading #{File.basename(source_filename)}.."
    S3Object.store(File.basename(source_filename), open(source_filename), bucket_name)
    puts "Stored!"

    exit_success!
  end
}