Amazon's Simple Storage Service is a very cheap and reliable storage infrastructure with a pay-as-you-go payment plan where you only need to pay for what you use. Amazon S3 provides 99.999999% data reliability, high data availability at a very nominal cost. It is one of the most suited solutions for small websites/businesses who can spend according to their usage as well get the best storage solution.

S3 Basics

Amazon S3 has a concept of buckets which is analogous to directories, but sub-directories i.e. buckets within buckets cannot be created. In the following code example we'll look a basic bucket operations.

Working With S3 Objects

In S3 terminology files inside buckets are called objects, here we'll be looking a uploading, downloading & deleting objects. Please follow the code example to understand the usage and various ways to accomplish a task.

Advanced Usage & Access Control

In this section let's look into some advanced usage, and how to set access permissions on objects. First the following code snippet will help you know and understand some advanced features/functions of Amazon S3.

Code:

#!/usr/local/bin/ruby
require 'rubygems'
require 'aws-sdk'
# set credentials
AWS.config({
:access_key_id => '<AccessKey>',
:secret_access_key => '<SecretKey>',
})
# create new S3 object
s3 = AWS::S3.new
# select a bucket
my_bucket = s3.buckets['my_shiny_new_bucket']
# if you have to delete multiple files, you can delete them with a single request/call
my_bucket.objects.delete('my_file1.txt','my_file2.txt','my_file3.txt')
# you can list file based on any prefix string you specify
# the code below will list all objects key names starting with 'my_'
my_bucket.objects.with_prefix('my_').each do |obj|
puts obj.key
end
# you can check if a bucket exists
# the next line does not make any call to the S3 server
my_bucket = s3.buckets['my_old_bucket']
# the next line returns true or false
my_bucket.exists?

Next, let us look at ACL using which we can control who gets access like read,write, etc.