AWS-S3 is a Ruby implementation of Amazon's S3 REST API
AWS-S3 is a Ruby implementation of Amazon's S3 REST API
= AWS::S3
AWS::S3 is a Ruby library for Amazon's Simple Storage Service's REST API (http://aws.amazon.com/s3). Full documentation of the currently supported API can be found at http://docs.amazonwebservices.com/AmazonS3/2006-03-01.
== Getting started
To get started you need to require 'aws/s3':
% irb -rubygems irb(main):001:0> require 'aws/s3'
The AWS::S3 library ships with an interactive shell called s3sh. From within it, you have access to all the operations the library exposes from the command line.
% s3sh
Version
Before you can do anything, you must establish a connection using Base.establish_connection!. A basic connection would look something like this:
AWS::S3::Base.establish_connection!( :access_key_id => 'abc', :secret_access_key => '123' )
The minimum connection options that you must specify are your access key id and your secret access key.
(If you don't already have your access keys, all you need to sign up for the S3 service is an account at Amazon. You can sign up for S3 and get access keys by visiting http://aws.amazon.com/s3.)
For convenience, if you set two special environment variables with the value of your access keys, the console will automatically create a default connection for you. For example:
% cat .amazon_keys export AMAZON_ACCESS_KEY_ID='abcdefghijklmnop' export AMAZON_SECRET_ACCESS_KEY='1234567891012345'
Then load it in your shell's rc file.
% cat .zshrc if [[ -f "$HOME/.amazon_keys" ]]; then source "$HOME/.amazon_keys"; fi
See more connection details at AWS::S3::Connection::Management::ClassMethods.
== AWS::S3 Basics === The service, buckets and objects
The three main concepts of S3 are the service, buckets and objects.
==== The service
The service lets you find out general information about your account, like what buckets you have.
Service.buckets
==== Buckets
Buckets are containers for objects (the files you store on S3). To create a new bucket you just specify its name.
Bucket.create('jukebox')
Bucket names must be unique across the entire S3 system, sort of like domain names across the internet. If you try to create a bucket with a name that is already taken, you will get an error.
Assuming the name you chose isn't already taken, your new bucket will now appear in the bucket list:
Service.buckets
Once you have succesfully created a bucket you can fetch it by name using Bucket.find.
music_bucket = Bucket.find('jukebox')
The bucket that is returned will contain a listing of all the objects in the bucket.
music_bucket.objects.size
If all you are interested in is the objects of the bucket, you can get to them directly using Bucket.objects.
Bucket.objects('jukebox').size
By default all objects will be returned, though there are several options you can use to limit what is returned, such as specifying that only objects whose name is after a certain place in the alphabet be returned, and etc. Details about these options can be found in the documentation for Bucket.find.
To add an object to a bucket you specify the name of the object, its value, and the bucket to put it in.
file = 'black-flowers.mp3' S3Object.store(file, open(file), 'jukebox')
You'll see your file has been added to it:
music_bucket.objects
You can treat your bucket like a hash and access objects by name:
jukebox['black-flowers.mp3']
In the event that you want to delete a bucket, you can use Bucket.delete.
Bucket.delete('jukebox')
Keep in mind, like unix directories, you can not delete a bucket unless it is empty. Trying to delete a bucket that contains objects will raise a BucketNotEmpty exception.
Passing the :force => true option to delete will take care of deleting all the bucket's objects for you.
Bucket.delete('photos', :force => true)
==== Objects
S3Objects represent the data you store on S3. They have a key (their name) and a value (their data). All objects belong to a bucket.
You can store an object on S3 by specifying a key, its data and the name of the bucket you want to put it in:
S3Object.store('me.jpg', open('headshot.jpg'), 'photos')
The content type of the object will be inferred by its extension. If the appropriate content type can not be inferred, S3 defaults to binary/octet-stream.
If you want to override this, you can explicitly indicate what content type the object should have with the :content_type option:
file = 'black-flowers.m4a' S3Object.store( file, open(file), 'jukebox', :content_type => 'audio/mp4a-latm' )
You can read more about storing files on S3 in the documentation for S3Object.store.
If you just want to fetch an object you've stored on S3, you just specify its name and its bucket:
picture = S3Object.find 'headshot.jpg', 'photos'
N.B. The actual data for the file is not downloaded in both the example where the file appeared in the bucket and when fetched directly. You get the data for the file like this:
picture.value
You can fetch just the object's data directly:
S3Object.value 'headshot.jpg', 'photos'
Or stream it by passing a block to stream:
open('song.mp3', 'w') do |file| S3Object.stream('song.mp3', 'jukebox') do |chunk| file.write chunk end end
The data of the file, once download, is cached, so subsequent calls to value won't redownload the file unless you tell the object to reload its value:
song.value(:reload)
Other functionality includes:
S3Object.exists? 'headshot.jpg', 'photos'
S3Object.copy 'headshot.jpg', 'headshot2.jpg', 'photos'
S3Object.rename 'headshot.jpg', 'portrait.jpg', 'photos'
S3Object.delete 'headshot.jpg', 'photos'
==== More about objects and their metadata
You can find out the content type of your object with the content_type method:
song.content_type
You can change the content type as well if you like:
song.content_type = 'application/pdf' song.store
(Keep in mind that due to limitiations in S3's exposed API, the only way to change things like the content_type is to PUT the object onto S3 again. In the case of large files, this will result in fully re-uploading the file.)
A bevie of information about an object can be had using the about method:
pp song.about {"last-modified" => "Sat, 28 Oct 2006 21:29:26 GMT", "content-type" => "binary/octet-stream", "etag" => ""dc629038ffc674bee6f62eb64ff3a"", "date" => "Sat, 28 Oct 2006 21:30:41 GMT", "x-amz-request-id" => "B7BC68F55495B1C8", "server" => "AmazonS3", "content-length" => "3418766"}
You can get and set metadata for an object:
song.metadata
song.metadata[:album] = "A River Ain't Too Much To Love"
song.metadata[:released] = 2005 pp song.metadata {"x-amz-meta-released" => 2005, "x-amz-meta-album" => "A River Ain't Too Much To Love"} song.store
That metadata will be saved in S3 and is hence forth available from that object:
song = S3Object.find('black-flowers.mp3', 'jukebox') pp song.metadata {"x-amz-meta-released" => "2005", "x-amz-meta-album" => "A River Ain't Too Much To Love"} song.metadata[:released]
song.metadata[:released] = 2006 pp song.metadata {"x-amz-meta-released" => 2006, "x-amz-meta-album" => "A River Ain't Too Much To Love"}
==== Streaming uploads
When storing an object on the S3 servers using S3Object.store, the data argument can be a string or an I/O stream. If data is an I/O stream it will be read in segments and written to the socket incrementally. This approach may be desirable for very large files so they are not read into memory all at once.
S3Object.store('greeting.txt', 'hello world!', 'marcel')
S3Object.store('roots.mpeg', open('roots.mpeg'), 'marcel')
== Setting the current bucket ==== Scoping operations to a specific bucket
If you plan on always using a specific bucket for certain files, you can skip always having to specify the bucket by creating a subclass of Bucket or S3Object and telling it what bucket to use:
class JukeBoxSong torrent_for:
S3Object.torrent_for 'kiss.jpg', 'marcel'
Or just call the torrent method if you already have the object:
song = S3Object.find 'kiss.jpg', 'marcel' song.torrent
Calling grant_torrent_access_to on a object will allow anyone to anonymously fetch the torrent file for that object:
S3Object.grant_torrent_access_to 'kiss.jpg', 'marcel'
Anonymous requests to
http://s3.amazonaws.com/marcel/kiss.jpg?torrent
will serve up the torrent file for that object.
== Access control ==== Using canned access control policies
By default buckets are private. This means that only the owner has access rights to the bucket and its objects. Objects in that bucket inherit the permission of the bucket unless otherwise specified. When an object is private, the owner can generate a signed url that exposes the object to anyone who has that url. Alternatively, buckets and objects can be given other access levels. Several canned access levels are defined:
You can set a canned access level when you create a bucket or an object by using the :access option:
S3Object.store( 'kiss.jpg', data, 'marcel', :access => :public_read )
Since the image we created is publicly readable, we can access it directly from a browser by going to the corresponding bucket name and specifying the object's key without a special authenticated url:
http://s3.amazonaws.com/marcel/kiss.jpg
==== Building custum access policies
For both buckets and objects, you can use the acl method to see its access control policy:
policy = S3Object.acl('kiss.jpg', 'marcel') pp policy.grants [#, #]
Policies are made up of one or more grants which grant a specific permission to some grantee. Here we see the default FULL_CONTROL grant to the owner of this object. There is also READ permission granted to the Allusers Group, which means anyone has read access for the object.
Say we wanted to grant access to anyone to read the access policy of this object. The current READ permission only grants them permission to read the object itself (for example, from a browser) but it does not allow them to read the access policy. For that we will need to grant the AllUsers group the READ_ACP permission.
First we'll create a new grant object:
grant = ACL::Grant.new
grant.permission = 'READ_ACP'
Now we need to indicate who this grant is for. In other words, who the grantee is:
grantee = ACL::Grantee.new
There are three ways to specify a grantee: 1) by their internal amazon id, such as the one returned with an object's Owner, 2) by their Amazon account email address or 3) by specifying a group. As of this writing you can not create custom groups, but Amazon does provide three already: AllUsers, Authenticated and LogDelivery. In this case we want to provide the grant to all users. This effectively means "anyone"
No open issues yet, or sync has not completed.