AWS SDK for Ruby Developer Guide … · Working with Rubyin the Elastic Beanstalk Developer Guide....

127
AWS SDK for Ruby Developer Guide Release 1.0 Amazon Web Services Mar 10, 2017

Transcript of AWS SDK for Ruby Developer Guide … · Working with Rubyin the Elastic Beanstalk Developer Guide....

Page 1: AWS SDK for Ruby Developer Guide … · Working with Rubyin the Elastic Beanstalk Developer Guide. For deploying a Ruby on Rails application with AWS OpsWorks, seeDeploying Ruby on

AWS SDK for Ruby Developer GuideRelease 1.0

Amazon Web Services

Mar 10, 2017

Page 2: AWS SDK for Ruby Developer Guide … · Working with Rubyin the Elastic Beanstalk Developer Guide. For deploying a Ruby on Rails application with AWS OpsWorks, seeDeploying Ruby on
Page 3: AWS SDK for Ruby Developer Guide … · Working with Rubyin the Elastic Beanstalk Developer Guide. For deploying a Ruby on Rails application with AWS OpsWorks, seeDeploying Ruby on

Contents

i

Page 4: AWS SDK for Ruby Developer Guide … · Working with Rubyin the Elastic Beanstalk Developer Guide. For deploying a Ruby on Rails application with AWS OpsWorks, seeDeploying Ruby on

ii

Page 5: AWS SDK for Ruby Developer Guide … · Working with Rubyin the Elastic Beanstalk Developer Guide. For deploying a Ruby on Rails application with AWS OpsWorks, seeDeploying Ruby on

CHAPTER 1

AWS SDK for Ruby Developer Guide

Welcome to the AWS SDK for Ruby.

The AWS SDK for Ruby helps take the complexity out of coding by providing Ruby classes for almost allAWS services, including Amazon Simple Storage Service, Amazon Elastic Compute Cloud, and AmazonDynamoDB. For a complete list of services supported by the AWS SDK for Ruby, see the SupportedServices section of the AWS SDK for Ruby Readme file.

1.1 About This Guide

The AWS SDK for Ruby Developer Guide provides information about how to install, set up, and use theAWS SDK for Ruby to create Ruby applications that use AWS services.

This guide contains the following sections:

Getting Started with the AWS SDK for Ruby Describes how to set up and use the AWS SDK for Ruby.

Hello World Tutorial Steps you through creating an application using the AWS SDK for Ruby.

Programming with the AWS SDK for Ruby Provides general information about developing software withthe AWS SDK for Ruby.

AWS SDK for Ruby Code Examples Provides code examples that developers can use to program AWSservices with the AWS SDK for Ruby.

Document History Describes the history of this document.

1.2 Additional Documentation and Resources

For more resources for AWS SDK for Ruby developers, see the following:

• AWS SDK for Ruby API Reference

• Developer blog

• Developer forums (you must have an AWS account to access the forums)

• Gitter channel

1

Page 6: AWS SDK for Ruby Developer Guide … · Working with Rubyin the Elastic Beanstalk Developer Guide. For deploying a Ruby on Rails application with AWS OpsWorks, seeDeploying Ruby on

AWS SDK for Ruby Developer Guide, Release 1.0

• @awsforruby on Twitter

• On GitHub:

– Releases (includes source, gems, and documentation)

– Source

– Change log

– Migration Guide

– Issues

– Feature requests

– Upgrading notes

1.2.1 Deploying to the AWS Cloud

You can use AWS services such as AWS Elastic Beanstalk, AWS OpsWorks, and AWS CodeDeploy todeploy your application to the AWS Cloud. For deploying Ruby applications with Elastic Beanstalk, seeWorking with Ruby in the Elastic Beanstalk Developer Guide. For deploying a Ruby on Rails applicationwith AWS OpsWorks, see Deploying Ruby on Rails Applications to AWS OpsWorks. For an overview ofAWS deployment services, see Overview of Deployment Options on AWS.

2 Chapter 1. AWS SDK for Ruby Developer Guide

Page 7: AWS SDK for Ruby Developer Guide … · Working with Rubyin the Elastic Beanstalk Developer Guide. For deploying a Ruby on Rails application with AWS OpsWorks, seeDeploying Ruby on

CHAPTER 2

Getting Started with the AWS SDK for Ruby

If you’re new to the AWS SDK for Ruby, you should start here. This section contains information aboutinstalling, setting up, and using the SDK to create a Ruby application to access Amazon S3.

2.1 QuickStart Guide to Using the AWS SDK for Ruby

This section shows you how to use the AWS SDK for Ruby to create a simple Ruby application that listsyour Amazon S3 buckets.

• If you haven’t installed the SDK, see Installing the AWS SDK for Ruby.

• If you haven’t configured the SDK, see Configuring the AWS SDK for Ruby.

2.1.1 Write the Code

The following example lists the names of up to 50 of your buckets. Copy the code and save it asbuckets.rb. Note that although the Resource object is created in the us-west-2 region, Amazon S3returns buckets to which you have access, regardless of the region.

require 'aws-sdk'

s3 = Aws::S3::Resource.new(region: 'us-west-2')

s3.buckets.limit(50).each do |b|puts "#{b.name}"

end

2.1.2 Run the Code

Enter the following command to execute buckets.rb.

ruby buckets.rb

3

Page 8: AWS SDK for Ruby Developer Guide … · Working with Rubyin the Elastic Beanstalk Developer Guide. For deploying a Ruby on Rails application with AWS OpsWorks, seeDeploying Ruby on

AWS SDK for Ruby Developer Guide, Release 1.0

2.1.3 Note for Windows users

When you use SSL certificates on Windows and run your Ruby code, you will see an error similar to thefollowing.

C:\Ruby>ruby buckets.rbC:/Ruby200-x64/lib/ruby/2.0.0/net/http.rb:921:in `connect': SSL_connect→˓returned=1 errno=0 state=SSLv3 read server certificate B: certificate→˓verify failed (Seahorse::Client::NetworkingError)

from C:/Ruby200-x64/lib/ruby/2.0.0/net/http.rb:921:in `block in→˓connect'

from C:/Ruby200-x64/lib/ruby/2.0.0/timeout.rb:66:in `timeout'from C:/Ruby200-x64/lib/ruby/2.0.0/net/http.rb:921:in `connect'from C:/Ruby200-x64/lib/ruby/2.0.0/net/http.rb:862:in `do_start'from C:/Ruby200-x64/lib/ruby/2.0.0/net/http.rb:857:in `start'

...

To fix this issue, add the following line to your Ruby source file, somewhere before your first AWS call.

Aws.use_bundled_cert!

2.2 Installing the AWS SDK for Ruby

This section includes prerequisites and installation instructions.

2.2.1 Prerequisites

Before you install the AWS SDK for Ruby, you need an AWS account and Ruby version 1.9 or later.

If you don’t have an AWS account, use the following procedure to create one.

To sign up for AWS

1. Open http://aws.amazon.com/ and choose Create an AWS Account.

2. Follow the online instructions.

2.2.2 Installing the AWS SDK for Ruby

If your project uses Bundler, add the following line to your Gemfile to add the AWS SDK for Ruby toyour project.

gem aws-sdk

If you don’t use Bundler, the easiest way to install the SDK is to use RubyGems. To install the latestversion of the SDK, use the following command.

4 Chapter 2. Getting Started with the AWS SDK for Ruby

Page 9: AWS SDK for Ruby Developer Guide … · Working with Rubyin the Elastic Beanstalk Developer Guide. For deploying a Ruby on Rails application with AWS OpsWorks, seeDeploying Ruby on

AWS SDK for Ruby Developer Guide, Release 1.0

gem install aws-sdk

If the previous command fails on your Unix-based system, use sudo to install the SDK, as shown in thefollowing command.

sudo gem install aws-sdk

2.3 Configuring the AWS SDK for Ruby

Learn how to configure the AWS SDK for Ruby. To use the SDK, you must set either AWS credentials orcreate an AWS STS access token, and set the AWS Region you want to use.

2.3.1 Setting AWS Credentials

Before you can use the AWS SDK for Ruby to make a call to an AWS service, you must set the AWSaccess credentials that the SDK will use to verify your access to AWS services and resources.

The AWS SDK for Ruby searches for credentials in the following order:

1. Setting Credentials in a Client Object

2. Setting Credentials Using Aws.config

3. Setting Credentials Using Environment Variables

4. Setting Shared Credentials

5. Setting Credentials Using IAM

The following sections describe the various ways you can set credentials, starting with the most flexibleapproach. For more information about AWS credentials and recommended approaches for credentialmanagement, see AWS Security Credentials in the Amazon Web Services General Reference.

Setting Shared Credentials

Set shared credentials in the AWS credentials profile file on your local system.

On Unix-based systems, such as Linux or OS X, this file is located in the following location.

~/.aws/credentials

On Windows, this file is located in the following location.

%HOMEPATH%\.aws\credentials

This file must have the following format, where default is the name of the default configuration profilegiven to these credentials, your_access_key_id is the value of your access key, andyour_secret_access_key is the value of your secret access key.

2.3. Configuring the AWS SDK for Ruby 5

Page 10: AWS SDK for Ruby Developer Guide … · Working with Rubyin the Elastic Beanstalk Developer Guide. For deploying a Ruby on Rails application with AWS OpsWorks, seeDeploying Ruby on

AWS SDK for Ruby Developer Guide, Release 1.0

[default]aws_access_key_id = your_access_key_idaws_secret_access_key = your_secret_access_key

Setting Credentials Using Environment Variables

Set the AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY environment variables.

Use the export command to set these variables on Unix-based systems, such as Linux or OS X. Thefollowing example sets the value of your access key to your_access_key_id and the value of yoursecret access key to your_secret_access_key.

export AWS_ACCESS_KEY_ID=your_access_key_idexport AWS_SECRET_ACCESS_KEY=your_secret_access_key

To set these variables on Windows, use the set command, as shown in the following example.

set AWS_ACCESS_KEY_ID=your_access_key_idset AWS_SECRET_ACCESS_KEY=your_secret_access_key

Setting Credentials Using Aws.config

Set the credentials in your code by updating the values in the Aws.config hash.

The following example sets the value of your access key to your_access_key_id and the value ofyour secret access key to your_secret_access_key. Any client or resource you create subsequentlywill use these credentials.

Aws.config.update({credentials: Aws::Credentials.new('your_access_key_id', 'your_secret_

→˓access_key')})

Setting Credentials in a Client Object

Set the credentials in your code by specifying them when you create an AWS client.

The following example creates an Amazon S3 client using the access key your_access_key_id andthe secret access key your_secret_access_key.

s3 = Aws::S3::Client.new(access_key_id: 'your_access_key_id',secret_access_key: 'your_secret_access_key'

)

6 Chapter 2. Getting Started with the AWS SDK for Ruby

Page 11: AWS SDK for Ruby Developer Guide … · Working with Rubyin the Elastic Beanstalk Developer Guide. For deploying a Ruby on Rails application with AWS OpsWorks, seeDeploying Ruby on

AWS SDK for Ruby Developer Guide, Release 1.0

Setting Credentials Using IAM

For an Amazon Elastic Compute Cloud instance, create an IAM role, and then give your Amazon EC2instance access to that role. For more information, see IAM Roles for Amazon EC2 in the Amazon EC2User Guide for Linux Instances or IAM Roles for Amazon EC2 in the Amazon EC2 User Guide forWindows Instances.

2.3.2 Creating an AWS STS Access Token

Use the Aws::AssumeRoleCredentials method to create an AWS STS access token.

The following example uses an access token to create an Amazon S3 client object, wherelinked::account::arn is the Amazon Resource Name (ARN) of the role to assume andsession-name is an identifier for the assumed role session.

role_credentials = Aws::AssumeRoleCredentials.new(client: Aws::STS::Client.new,role_arn: "linked::account::arn",role_session_name: "session-name"

)

s3 = Aws::S3::Client.new(credentials: role_credentials)

2.3.3 Setting a Region

You need to set a region when using most AWS services. You can set the AWS Region in ways similar tosetting your AWS credentials. The AWS SDK for Ruby searches for a region in the following order:

• Setting the Region in a Client or Resource Object

• Setting the Region Using Aws.config

• Setting the Region Using Environment Variables

The rest of this section describes how to set a region, starting with the most flexible approach.

Setting the Region Using Environment Variables

Set the region by setting the AWS_REGION environment variable.

Use the export command to set this variable on Unix-based systems, such as Linux or OS X. Thefollowing example sets the region to us-west-2.

export AWS_REGION=us-west-2

To set this variable on Windows, use the set command. The following example sets the region tous-west-2.

set AWS_REGION=us-west-2

2.3. Configuring the AWS SDK for Ruby 7

Page 12: AWS SDK for Ruby Developer Guide … · Working with Rubyin the Elastic Beanstalk Developer Guide. For deploying a Ruby on Rails application with AWS OpsWorks, seeDeploying Ruby on

AWS SDK for Ruby Developer Guide, Release 1.0

Setting the Region Using Aws.config

Set the region by adding a region value to the Aws.config hash. The following example updates theAws.config hash to use the us-west-1 region.

Aws.config.update({region: 'us-west-1'})

Any clients or resources you subsequently create are bound to this region.

Setting the Region in a Client or Resource Object

Set the region when you create an AWS client or resource. The following example creates an Amazon S3resource object in the us-west-1 region.

s3 = Aws::S3::Resource.new(region: 'us-west-1')

2.3.4 Setting a Nonstandard Endpoint

If you need to use a nonstandard endpoint in the region you’ve selected, add an endpoint entry toAws.config or set the endpoint: when creating a service client or resource object. The followingexample creates an Amazon S3 resource object in the other_endpoint endpoint.

s3 = Aws::S3::Resource.new(endpoint: other_endpoint)

2.4 Using the AWS SDK for Ruby REPL

Developers can use aws.rb, the interactive command-line read-evaluate-print loop (REPL) console toolthat is part of the aws-sdk-core gem.

Although aws.rb does work with the Interactive Ruby Shell (irb), we recommend that you install pry,which provides a more powerful REPL environment.

Use the following command to install pry.

gem install pry

To use aws.rb, you invoke it in a console window using one of the following two command lines.

aws.rbaws.rb -v

The second command line invokes the REPL with extensive HTTP wire logging, which providesinformation about the communication between the AWS SDK for Ruby and AWS. Use this command linewith caution, however, because it also adds overhead that can make your code run slower.

The REPL defines a helper object for every service class. Downcase the service module name to get thename of the helper object. For example, the names of the Amazon S3 and Amazon EC2 helper objects ares3 and ec2, respectively.

8 Chapter 2. Getting Started with the AWS SDK for Ruby

Page 13: AWS SDK for Ruby Developer Guide … · Working with Rubyin the Elastic Beanstalk Developer Guide. For deploying a Ruby on Rails application with AWS OpsWorks, seeDeploying Ruby on

AWS SDK for Ruby Developer Guide, Release 1.0

2.5 Using the SDK with Ruby on Rails

Ruby on Rails provides a web development framework for Ruby that makes it easy to create websites withRuby.

The AWS SDK for Ruby provides a gem to enable easy integration with Rails. You can use AWS ElasticBeanstalk, AWS OpsWorks, or AWS CodeDeploy to deploy and run your Rails applications in the AWSCloud.

2.5.1 Integrating the AWS SDK for Ruby with Rails

AWS provides a gemfile, aws-sdk-rails, that supports integration of the AWS SDK for Ruby withRails. You can view its GitHub repository at https://github.com/aws/aws-sdk-rails.

Add the gem to your application’s Gemfile, as shown in the following example.

gem 'aws-sdk-rails'

The gem includes the AWS SDK for Ruby, so adding the gem is all you need to do to add AWS support toyour Rails application.

2.5.2 Amazon SES Support for ActionMailer

When you use the aws-sdk-rails gem in a config/environments file of your Rails project (forexample, config/environments/production.rb), you can use Amazon Simple Email Service(Amazon SES) as the back end for the ActionMailer class, as shown in the following example.

config.action_mailer.delivery_method = :aws_sdk

For more information about ActionMailer, see the Action Mailer Basics on the Ruby on Rails website.

2.5.3 Logging

The aws-sdk-rails gem configures the SDK logger to use Rails.logger.

The gem also configures the SDK log messages to use the :info log level. You can change the log levelby setting :log_level in the Aws.config hash. The following example sets the log level to :debug.

Aws.config.update({log_level: :debug})

2.6 Migrating from version 1 to version 2 of the AWS SDK for Ruby

The purpose of this topic is to help you migrate from version 1 of the AWS SDK for Ruby to version 2.

2.5. Using the SDK with Ruby on Rails 9

Page 14: AWS SDK for Ruby Developer Guide … · Working with Rubyin the Elastic Beanstalk Developer Guide. For deploying a Ruby on Rails application with AWS OpsWorks, seeDeploying Ruby on

AWS SDK for Ruby Developer Guide, Release 1.0

2.6.1 Side-by-Side Usage

It is not necessary to replace the version 1 AWS SDK for Ruby with version 2. You can use them togetherin the same application. See this blog post for more information.

A quick example follows:

require 'aws-sdk-v1' # version 1require 'aws-sdk' # version 2

s3 = AWS::S3::Client.new # version 1s3 = Aws::S3::Client.new # version 2

You do not need to rewrite existing working version 1 code to start using the version 2 SDK. A validmigration strategy is to only write new code against the version 2 SDK.

2.6.2 General Differences

Version 2 differs from version 1 in a number of important ways.

• Different root namespace, Aws vs AWS. This enables side-by-side usage.

• Aws.config is now a vanilla Ruby hash, instead of a method.

• Strict constructor options - When constructing a client or resource object in the version 1 SDK,unknown constructor options are ignored. In version 2, unknown constructor options trigger anArgumentError. For example:

# version 1AWS::S3::Client.new(http_reed_timeout: 10)# oops, typo'd option is ignored

# version 2Aws::S3::Client.new(http_reed_timeout: 10)# => raises ArgumentError

2.6.3 Client Differences

Between version 1 and version 2, the client classes have the fewest external differences. Many serviceclients will have compatible interfaces after client construction. Some important differences:

• Aws::S3::Client - The version 1 Amazon S3 client class was hand-coded. Version 2 isgenerated from a service model. Method names an inputs are very different in version 2.

• Aws::EC2::Client- Version 2 uses plural names for output lists, version 1 uses the suffix _set.For example:

# version 1resp = AWS::EC2::Client.new.describe_security_groupsresp.security_group_set#=> [...]

10 Chapter 2. Getting Started with the AWS SDK for Ruby

Page 15: AWS SDK for Ruby Developer Guide … · Working with Rubyin the Elastic Beanstalk Developer Guide. For deploying a Ruby on Rails application with AWS OpsWorks, seeDeploying Ruby on

AWS SDK for Ruby Developer Guide, Release 1.0

# version 2resp = Aws::EC2::Client.new.describe_security_groupsresp.security_groups#=> [...]

• Aws::SWF::Client - Version two uses structured responses, where version 1 uses vanilla Rubyhashes.

• Service class renames - Version 2 uses a different name for multiple services:

– AWS::SimpleWorkflow has become Aws::SWF

– AWS::ELB has become Aws::ElasticLoadBalancing

– AWS::SimpleEmailService has become Aws::SES

• Client configuration options - Some of the version 1 configuration options have been renamed inversion 2. Others have been removed or replaced. Here are the primary changes:

– :use_ssl has been removed. Version 2 uses SSL everywhere. To disable SSL you mustconfigure an :endpoint that uses http://.

– :ssl_ca_file => :ssl_ca_bundle

– :ssl_ca_path => :ssl_ca_directory

– Added :ssl_ca_store.

– :endpoint must now be a fully qualified HTTP or HTTPS uri instead of a hostname.

– Removed :*_port options for each service, replaced by :endpoint.

– :user_agent_prefix is now :user_agent_suffix

2.6.4 Resource Differences

There are significant differences between the resource interfaces in version 1 and version 2. Version 1 wasentirely hand-coded, where as version 2 resource interfaces are generated from a model. Version 2 resourceinterfaces are significantly more consistent. Some of the systemic differences include:

• Separate resource class - In version 2, the service name is a module and not a class. In this module isthe resource interface:

# version 1s3 = AWS::S3.new

# version 2s3 = Aws::S3::Resource.new

• Referencing resources - The version 2 SDK separates collections and individual resource getters intotwo different methods:

2.6. Migrating from version 1 to version 2 of the AWS SDK for Ruby 11

Page 16: AWS SDK for Ruby Developer Guide … · Working with Rubyin the Elastic Beanstalk Developer Guide. For deploying a Ruby on Rails application with AWS OpsWorks, seeDeploying Ruby on

AWS SDK for Ruby Developer Guide, Release 1.0

# version 1s3.buckets['bucket-name'].objects['key'].delete

# version 2s3.bucket('bucket-name').object('key').delete

• Batch operations - In version 1, all batch operations were hand-coded utilities. In version 2, manybatch operations are auto-generated batching operations over the API. Version 2 batchinginterfaces are very different from version 1.

12 Chapter 2. Getting Started with the AWS SDK for Ruby

Page 17: AWS SDK for Ruby Developer Guide … · Working with Rubyin the Elastic Beanstalk Developer Guide. For deploying a Ruby on Rails application with AWS OpsWorks, seeDeploying Ruby on

CHAPTER 3

Hello World Tutorial

This tutorial shows you how to use the AWS SDK for Ruby to create a command-line program thatperforms some common Amazon S3 operations.

3.1 Using the AWS SDK for Ruby in Your Program

Add a require statement to the top of your Ruby source file so you can use the classes and methodsprovided by the AWS SDK for Ruby.

require 'aws-sdk'

3.2 Creating an Amazon S3 Resource

Create an Aws::S3::Resource object in the appropriate region. The following example creates an AmazonS3 resource object in the us-west-2 region. Note that the region is not important as Amazon S3resources are not specific to a region.

s3 = Aws::S3::Resource.new(region: 'us-west-2')

3.3 Creating a Bucket

To store anything on Amazon S3, you’ll need a bucket to put it in.

Create an Aws::S3::Bucket object. The following example creates the bucket my_bucket with the namemy-bucket.

my_bucket = s3.bucket('my-bucket')my_bucket.create

13

Page 18: AWS SDK for Ruby Developer Guide … · Working with Rubyin the Elastic Beanstalk Developer Guide. For deploying a Ruby on Rails application with AWS OpsWorks, seeDeploying Ruby on

AWS SDK for Ruby Developer Guide, Release 1.0

3.4 Adding a File to the Bucket

Use the #upload_file method to add a file to the bucket. The following example adds the file namedmy_file to the bucket named my-bucket.

name = File.basename 'my_file'obj = s3.bucket('my-bucket').object(name)obj.upload_file('my_file')

3.5 Listing the Contents of a Bucket

To list the contents of a bucket, use the Aws::S3::Bucket:Objects method. The following example lists upto 50 bucket items for the bucket my-bucket.

my_bucket.objects.limit(50).each do |obj|puts " #{obj.key} => #{obj.etag}"

end

3.6 Complete Program

The following is the entire hello-s3.rb program.

require 'aws-sdk'

NO_SUCH_BUCKET = "The bucket '%s' does not exist!"

USAGE = <<DOC

Usage: hello-s3 bucket_name [operation] [file_name]

Where:bucket_name (required) is the name of the bucket

operation is the operation to perform on the bucket:create - creates a new bucketupload - uploads a file to the bucketlist - (default) lists up to 50 bucket items

file_name is the name of the file to upload,required when operation is 'upload'

DOC

# Set the name of the bucket on which the operations are performed# This argument is requiredbucket_name = nil

if ARGV.length > 0

14 Chapter 3. Hello World Tutorial

Page 19: AWS SDK for Ruby Developer Guide … · Working with Rubyin the Elastic Beanstalk Developer Guide. For deploying a Ruby on Rails application with AWS OpsWorks, seeDeploying Ruby on

AWS SDK for Ruby Developer Guide, Release 1.0

bucket_name = ARGV[0]else

puts USAGEexit 1

end

# The operation to perform on the bucketoperation = 'list' # defaultoperation = ARGV[1] if (ARGV.length > 1)

# The file name to use with 'upload'file = nilfile = ARGV[2] if (ARGV.length > 2)

# Get an Amazon S3 resources3 = Aws::S3::Resource.new(region: 'us-west-2')

# Get the bucket by namebucket = s3.bucket(bucket_name)

case operationwhen 'create'

# Create a bucket if it doesn't already existif bucket.exists?

puts "The bucket '%s' already exists!" % bucket_nameelse

bucket.createputs "Created new S3 bucket: %s" % bucket_name

end

when 'upload'if file == nil

puts "You must enter the name of the file to upload to S3!"exit

end

if bucket.exists?name = File.basename file

# Check if file is already in bucketif bucket.object(name).exists?

puts "#{name} already exists in the bucket"else

obj = s3.bucket(bucket_name).object(name)obj.upload_file(file)puts "Uploaded '%s' to S3!" % name

endelse

NO_SUCH_BUCKET % bucket_nameend

when 'list'if bucket.exists?

3.6. Complete Program 15

Page 20: AWS SDK for Ruby Developer Guide … · Working with Rubyin the Elastic Beanstalk Developer Guide. For deploying a Ruby on Rails application with AWS OpsWorks, seeDeploying Ruby on

AWS SDK for Ruby Developer Guide, Release 1.0

# Enumerate the bucket contents and object etagsputs "Contents of '%s':" % bucket_nameputs ' Name => GUID'

bucket.objects.limit(50).each do |obj|puts " #{obj.key} => #{obj.etag}"

endelse

NO_SUCH_BUCKET % bucket_nameend

elseputs "Unknown operation: '%s'!" % operationputs USAGE

end

3.7 Running the Program

To list the contents of a bucket, use either of the following commands, where bucket-name is the nameof the bucket to list. We don’t have to include list because it is the default operation.

ruby hello-s3.rb bucket-name listruby hello-s3.rb bucket-name

To create a bucket, use the following command, where bucket-name is the name of the bucket you wantto create.

ruby hello-s3.rb bucket-name create

If Amazon S3 already has a bucket named bucket-name, the service issues an error message and doesnot create another copy.

After you create your bucket, you can upload an object to the bucket. The following command addsyour_file.txt to the bucket.

ruby hello-s3.rb bucket-name upload your_file.txt

3.8 Next Steps

Now that you’ve completed your first AWS SDK for Ruby application, here are some suggestions to extendthe code you just wrote:

• Use the buckets collection from the Aws::S3::Resource class to get a list of buckets.

• Use #get method from the Bucket class to download an object from the bucket.

• Use the code in Adding a File to the Bucket to confirm the item exists in the bucket, and then updatethat bucket item.

16 Chapter 3. Hello World Tutorial

Page 21: AWS SDK for Ruby Developer Guide … · Working with Rubyin the Elastic Beanstalk Developer Guide. For deploying a Ruby on Rails application with AWS OpsWorks, seeDeploying Ruby on

CHAPTER 4

Programming with the AWS SDK for Ruby

This section provides information about developing software with the AWS SDK for Ruby, including howto use some of the SDK’s advanced features.

4.1 Debugging Tip: Getting Wire Trace Information from a Client

You can get wire trace information from an AWS client when you create it by setting thehttp_wire_trace option. This information helps differentiate client changes, service issues, and usererrors. The following example creates an Amazon S3 client with wire tracing enabled.

s3 = Aws::S3::Client.new(http_wire_trace: true)

Given the following code and the argument bucket_name, the output displays a message that sayswhether a bucket with that name exists.

require 'aws-sdk'

s3 = Aws::S3::Resource.new(client: Aws::S3::Client.new(http_wire_trace: true))

if s3.bucket(ARGV[0]).exists?puts "Bucket #{ARGV[0]} exists"

elseputs "Bucket #{ARGV[0]} does not exist"

end

If the bucket exists, the output looks something like the following, where ACCESS_KEY is the value ofyour access key. (Returns were added to the HEAD line for readability.)

opening connection to bucket_name.s3-us-west-1.amazonaws.com:443...openedstarting SSL for bucket_name.s3-us-west-1.amazonaws.com:443...SSL established<- "HEAD / HTTP/1.1\r\n

Content-Type: \r\nAccept-Encoding: \r\nUser-Agent: aws-sdk-ruby2/2.2.7 ruby/2.1.7 x64-mingw32\r\nX-Amz-Date: 20160121T191751Z\r\n

17

Page 22: AWS SDK for Ruby Developer Guide … · Working with Rubyin the Elastic Beanstalk Developer Guide. For deploying a Ruby on Rails application with AWS OpsWorks, seeDeploying Ruby on

AWS SDK for Ruby Developer Guide, Release 1.0

Host: bucket_name.s3-us-west-1.amazonaws.com\r\nX-Amz-Content-Sha256:

→˓e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855\r\nAuthorization: AWS4-HMAC-SHA256 Credential=ACCESS_KEY/20160121/us-west-1/

→˓s3/aws4_request,SignedHeaders=host;x-amz-content-sha256;x-amz-date,

→˓Signature=2ca8301c5e829700940d3cc3bca2a3e8d79d177f2c046c34a1a285770db63820\r\nContent-Length: 0\r\nAccept: */*\r\n\r\n"

-> "HTTP/1.1 301 Moved Permanently\r\n"-> "x-amz-bucket-region: us-west-2\r\n"-> "x-amz-request-id: F3C75F33EF0792C4\r\n"-> "x-amz-id-2:→˓N6BzRLx8b68NmF50g1IxLzT+E4uWPuAIRe7Pl4XKl5STT4tfNO7gBsO8qrrAnG4CbVpU0iIRXmk=\r\n→˓"-> "Content-Type: application/xml\r\n"-> "Transfer-Encoding: chunked\r\n"-> "Date: Thu, 21 Jan 2016 19:17:54 GMT\r\n"-> "Server: AmazonS3\r\n"-> "\r\n"Conn keep-aliveBucket bucket_name exists

4.2 Stubbing Client Responses and Errors

Learn how to stub client responses and client errors in an AWS SDK for Ruby application.

4.2.1 Stubbing Client Responses

When you stub a response, the AWS SDK for Ruby disables network traffic and the client returns stubbed(or fake) data. If you don’t supply stubbed data, the client returns:

• Lists as empty arrays

• Maps as empty hashes

• Numeric values as zero

• Dates as now

The following example returns stubbed names for the list of Amazon S3 buckets.

require 'aws-sdk'

s3 = Aws::S3::Client.new(stub_responses: true)

bucket_data = s3.stub_data(:list_buckets, :buckets => [{name:'aws-sdk'},→˓{name:'aws-sdk2'}])s3.stub_responses(:list_buckets, bucket_data)

18 Chapter 4. Programming with the AWS SDK for Ruby

Page 23: AWS SDK for Ruby Developer Guide … · Working with Rubyin the Elastic Beanstalk Developer Guide. For deploying a Ruby on Rails application with AWS OpsWorks, seeDeploying Ruby on

AWS SDK for Ruby Developer Guide, Release 1.0

bucket_names = s3.list_buckets.buckets.map(&:name)

# List each bucket by namebucket_names.each do |name|puts name

end

Running this code displays the following.

aws-sdkaws-sdk2

Note: After you supply any stubbed data, the default values no longer apply for any remaining instanceattributes. This means that in the previous example, the remaining instance attribute, creation_date, isnot now but nil.

The AWS SDK for Ruby validates your stubbed data. If you pass in data of the wrong type, it raises anArgumentError exception. For example, if instead of the previous assignment to bucket_data, youused the following:

bucket_data = s3.stub_data(:list_buckets, buckets:['aws-sdk', 'aws-sdk2'])

The AWS SDK for Ruby raises two ArgumentError exceptions.

expected params[:buckets][0] to be a hashexpected params[:buckets][1] to be a hash

4.2.2 Stubbing Client Errors

You can also stub errors that the AWS SDK for Ruby raises for specific methods. The following exampledisplays Caught Timeout::Error error calling head_bucket on aws-sdk.

require 'aws-sdk'

s3 = Aws::S3::Client.new(stub_responses: true)s3.stub_responses(:head_bucket, Timeout::Error)

begins3.head_bucket({bucket: 'aws-sdk'})

rescue Exception => exputs "Caught #{ex.class} error calling 'head_bucket' on 'aws-sdk'"

end

4.2. Stubbing Client Responses and Errors 19

Page 24: AWS SDK for Ruby Developer Guide … · Working with Rubyin the Elastic Beanstalk Developer Guide. For deploying a Ruby on Rails application with AWS OpsWorks, seeDeploying Ruby on

AWS SDK for Ruby Developer Guide, Release 1.0

4.3 Paging Response Data

Some AWS calls provide paged responses to limit the amount of data returned with each response. A pageof data represents up to 1,000 items.

4.3.1 Paged Responses Are Enumerable

The simplest way to handle paged response data is to use the built-in enumerator in the response object, asshown in the following example.

s3 = Aws::S3::Client.new

s3.list_objects(bucket:'aws-sdk').each do |response|puts response.contents.map(&:key)

end

This yields one response object per API call made, and enumerates objects in the named bucket. The SDKretrieves additional pages of data to complete the request.

4.3.2 Handling Paged Responses Manually

To handle paging yourself, use the response’s next_page? method to verify there are more pages toretrieve, or use the last_page? method to verify there are no more pages to retrieve.

If there are more pages, use the next_page (notice there is no ?) method to retrieve the next page ofresults, as shown in the following example.

s3 = Aws::S3::Client.new

# Get the first page of dataresponse = s3.list_objects(bucket:'aws-sdk')

# Get additional pageswhile response.next_page? doresponse = response.next_page# Use the response data here...

end

Note: If you call the next_page method and there are no more pages to retrieve, the SDK raises anAws::PageableResponse::LastPageError exception.

4.3.3 Paged Data Classes

Paged data in the AWS SDK for Ruby is handled by the Aws::PageableResponse class, which is includedwith Seahorse::Client::Response to provide access to paged data.

20 Chapter 4. Programming with the AWS SDK for Ruby

Page 25: AWS SDK for Ruby Developer Guide … · Working with Rubyin the Elastic Beanstalk Developer Guide. For deploying a Ruby on Rails application with AWS OpsWorks, seeDeploying Ruby on

AWS SDK for Ruby Developer Guide, Release 1.0

4.4 Using Waiters

Waiters are utility methods that poll for a particular state to occur on a client. Waiters can fail after anumber of attempts at a polling interval defined for the service client. For an example of how a waiter isused, see Creating a Simple Table with a Single Primary Key.

4.4.1 Invoking a Waiter

To invoke a waiter, call #wait_until on a service client. In the following example, a waiter waits untilthe instance i-12345678 is running before continuing.

ec2 = Aws::EC2::Client.new

beginec2.wait_until(:instance_running, instance_ids:['i-12345678'])puts "instance running"

rescue Aws::Waiters::Errors::WaiterFailed => errorputs "failed waiting for instance running: #{error.message}"

end

The first parameter is the waiter name, which is specific to the service client and indicates which operationis being waited for. The second parameter is a hash of parameters that are passed to the client methodcalled by the waiter, which varies according to the waiter name.

For a list of operations that can be waited for and the client methods called for each operation, see the#waiter_names and #wait_until field documentation for the client you are using.

4.4.2 Wait Failures

Waiters can fail with any of the following exceptions:

Aws::Waiters::Errors::FailureStateError A failure state was encountered while waiting.

Aws::Waiters::Errors::NoSuchWaiterError The specified waiter name is not defined for the clientbeing used.

Aws::Waiters::Errors::TooManyAttemptsError The number of attempts exceeded the waiter’smax_attempts value.

Aws::Waiters::Errors::UnexpectedError An unexpected error occurred while waiting.

Aws::Waiters::Errors::WaiterFailed One of the wait states was exceeded or another failure occurredwhile waiting.

All of these errors—except NoSuchWaiterError—are based on WaiterFailed. To catch errors in awaiter, use WaiterFailed, as shown in the following example.

rescue Aws::Waiters::Errors::WaiterFailed => errorputs "failed waiting for instance running: #{error.message}"

end

4.4. Using Waiters 21

Page 26: AWS SDK for Ruby Developer Guide … · Working with Rubyin the Elastic Beanstalk Developer Guide. For deploying a Ruby on Rails application with AWS OpsWorks, seeDeploying Ruby on

AWS SDK for Ruby Developer Guide, Release 1.0

4.4.3 Configuring a Waiter

Each waiter has a default polling interval and a maximum number of attempts it will make before returningcontrol to your program. To set these values, use the max_attempts and delay: parameters in your#wait_until call. The following example waits for up to 25 seconds, polling every 5 seconds.

# Poll for ~25 secondsclient.wait_until(...) do |w|w.max_attempts = 5w.delay = 5

end

To disable wait failures, set the value of either of these parameters to nil.

4.4.4 Extending a Waiter

To modify the behavior of waiters, you can register callbacks that are triggered before each polling attemptand before waiting.

The following example implements an exponential backoff in a waiter by doubling the amount of time towait on every attempt.

ec2 = Aws::EC2::Client.new

ec2.wait_until(:instance_running, instance_ids:['i-12345678']) do |w|w.interval = 0 # disable normal sleepw.before_wait do |n, resp|

sleep(n ** 2)end

end

The following example disables the maximum number of attempts, and instead waits for 1 hour (3600seconds) before failing.

started_at = Time.nowclient.wait_until(...) do |w|# Disable max attemptsw.max_attempts = nil

# Poll for 1 hour, instead of a number of attemptsbefore_wait do |attempts, response|

throw :failure if Time.now - started_at > 3600end

end

4.5 Specifying a Client Timeout Duration

The following example creates an Amazon S3 client in the region us-west-2, and specifies to wait 5seconds between two retries on every client operation. By default, the SDK performs up to three retries,

22 Chapter 4. Programming with the AWS SDK for Ruby

Page 27: AWS SDK for Ruby Developer Guide … · Working with Rubyin the Elastic Beanstalk Developer Guide. For deploying a Ruby on Rails application with AWS OpsWorks, seeDeploying Ruby on

AWS SDK for Ruby Developer Guide, Release 1.0

with 15 seconds between retries, for a total of up to four attempts. Therefore, an operation could take 60seconds to time out, so the example could take 15 seconds to time out.

s3 = Aws::S3::Client.new(region: 'us-west-2', retry_limit: 2, http_open_→˓timeout: 5)

4.5. Specifying a Client Timeout Duration 23

Page 28: AWS SDK for Ruby Developer Guide … · Working with Rubyin the Elastic Beanstalk Developer Guide. For deploying a Ruby on Rails application with AWS OpsWorks, seeDeploying Ruby on

AWS SDK for Ruby Developer Guide, Release 1.0

24 Chapter 4. Programming with the AWS SDK for Ruby

Page 29: AWS SDK for Ruby Developer Guide … · Working with Rubyin the Elastic Beanstalk Developer Guide. For deploying a Ruby on Rails application with AWS OpsWorks, seeDeploying Ruby on

CHAPTER 5

AWS SDK for Ruby Code Examples

This section provides examples you can use to access AWS services by using the AWS SDK for Ruby.

5.1 Amazon CloudWatch Examples

You can use the following examples to access Amazon CloudWatch (CloudWatch) by using the AWS SDKfor Ruby. For more information about CloudWatch, see the CloudWatch Developer Guide.

Examples

5.1.1 Getting Information about All Alarms

The following example displays information about your CloudWatch alarms.

require 'aws-sdk'

client = Aws::CloudWatch::Client.new(region: 'us-west-2')

# use client.describe_alarms({alarm_names: ['Name1', 'Name2']})# to get information about alarms Name1 and Name2resp = client.describe_alarms

resp.metric_alarms.each do |alarm|puts 'Name: ' + alarm.alarm_nameputs 'State: ' + alarm.state_valueputs ' reason: ' + alarm.state_reasonputs 'Metric: ' + alarm.metric_nameputs 'Namespace: ' + alarm.namespaceputs 'Statistic: ' + alarm.statisticputs 'Dimensions (' + alarm.dimensions.length.to_s + '):'

alarm.dimensions.each do |d|puts ' Name: ' + d.nameputs ' Value: ' + d.value

end

puts 'Period: ' + alarm.period.to_s

25

Page 30: AWS SDK for Ruby Developer Guide … · Working with Rubyin the Elastic Beanstalk Developer Guide. For deploying a Ruby on Rails application with AWS OpsWorks, seeDeploying Ruby on

AWS SDK for Ruby Developer Guide, Release 1.0

puts 'Unit: ' + alarm.unit.to_sputs 'Eval periods: ' + alarm.evaluation_periods.to_sputs 'Threshold: ' + alarm.threshold.to_sputs 'Comp operator: ' + alarm.comparison_operatorputs

end

5.1.2 Creating an Alarm

The following example creates a CloudWatch alarm my-alarm that sends a message through the AmazonSNS topic with the ARN ARN when the Amazon S3 bucket my-bucket has more than 50 items in a 24-hourperiod.

require 'aws-sdk'

# Placeholder for put_metric_alarm argsargs = {}args[:alarm_name] = 'my-alarm'args[:alarm_description] = 'Triggers alarm when S3 bucket my-bucket has more→˓than 50 items'args[:alarm_actions] = 'ARN'args[:namespace] = 'AWS/S3'args[:metric_name] = 'NumberOfObjects'

dim1 = {}dim1[:name] = 'BucketName'dim1[:value] = 'my-bucket'

dim2 = {}dim2[:name] = 'StorageType'dim2[:value] = 'AllStorageTypes'

dimensions = []

dimensions << dim1dimensions << dim2

args[:dimensions] = dimensions

args[:statistic] = 'Maximum'

# NumberOfObjects REQUIRES this valueargs[:period] = 86400

# NumberOfObjects REQUIRES this valueargs[:unit] = nil

args[:evaluation_periods] = 1args[:threshold] = 50args[:comparison_operator] = 'GreaterThanThreshold'

26 Chapter 5. AWS SDK for Ruby Code Examples

Page 31: AWS SDK for Ruby Developer Guide … · Working with Rubyin the Elastic Beanstalk Developer Guide. For deploying a Ruby on Rails application with AWS OpsWorks, seeDeploying Ruby on

AWS SDK for Ruby Developer Guide, Release 1.0

cw = Aws::CloudWatch::Client.new(region: 'us-west-2')

cw.put_metric_alarm(args)

5.1.3 Enabling and Disabling Alarm Actions

An Amazon CloudWatch alarm watches a single metric over a time period you specify. The CloudWatchalarm performs one or more actions based on the value of the metric, relative to a given threshold over anumber of time periods. For more information, see Creating Amazon CloudWatch Alarms.

In this example, you use the AWS SDK for Ruby with CloudWatch to:

1. Enable an action for a CloudWatch alarm by using Aws::CloudWatch::Client#put_metric_alarm.

2. Disable all actions for an alarm by using Aws::CloudWatch::Client#disable_alarm_actions.

The complete code for this example is available on GitHub.

Prerequisites

Before running the example code, you need to install and configure the AWS SDK for Ruby, as describedin:

• Installing the AWS SDK for Ruby

• Configuring the AWS SDK for Ruby

You’ll also need to replace arn:aws:sns:REGION-ID:ACCOUNT-ID:TOPIC-NAME with the ARN for avalid Amazon SNS topic.

Example

require 'aws-sdk'

# Uncomment for Windows.# Aws.use_bundled_cert!

cw = Aws::CloudWatch::Client.new(region: 'us-east-1')

# Enable an action for an Amazon CloudWatch alarm.# If the alarm does not exist, create it.# If the alarm exists, update its settings.alarm_name = "TooManyObjectsInBucket"

cw.put_metric_alarm({alarm_name: alarm_name,alarm_description: "Alarm whenever an average of more than one object

→˓exists in the specified Amazon S3 bucket for more than one day.",actions_enabled: true, # Run actions if the alarm's state changes.metric_name: "NumberOfObjects",

5.1. Amazon CloudWatch Examples 27

Page 32: AWS SDK for Ruby Developer Guide … · Working with Rubyin the Elastic Beanstalk Developer Guide. For deploying a Ruby on Rails application with AWS OpsWorks, seeDeploying Ruby on

AWS SDK for Ruby Developer Guide, Release 1.0

alarm_actions: [ "arn:aws:sns:REGION-ID:ACCOUNT-ID:TOPIC-NAME" ], # Notify→˓this Amazon SNS topic only if the alarm's state changes to ALARM.namespace: "AWS/S3",statistic: "Average",dimensions: [

{name: "BucketName",value: "my-bucket"

},{

name: "StorageType",value: "AllStorageTypes"

}],period: 86400, # Daily (24 hours * 60 minutes * 60 seconds = 86400 seconds).unit: "Count",evaluation_periods: 1, # More than one day.threshold: 1, # One object.comparison_operator: "GreaterThanThreshold" # More than one object.

})

# Disable all actions for the alarm.cw.disable_alarm_actions({

alarm_names: [ alarm_name ]})

5.1.4 Getting Info about Custom Metrics

A CloudWatch alarm watches a single metric over a time period you specify. The CloudWatch alarmperforms one or more actions based on the value of the metric, relative to a given threshold over a numberof time periods. For more information, see Creating Amazon CloudWatch Alarms.

In this example, you use the AWS SDK for Ruby with CloudWatch to:

1. Send custom metrics to CloudWatch by using Aws::CloudWatch::Client#put_metric_data.

2. Get information about custom metrics by using Aws::CloudWatch::Client#list_metrics-instance.

Prerequisites

Before running the example code, you need to install and configure the AWS SDK for Ruby, as describedin:

• Installing the AWS SDK for Ruby

• Configuring the AWS SDK for Ruby

28 Chapter 5. AWS SDK for Ruby Code Examples

Page 33: AWS SDK for Ruby Developer Guide … · Working with Rubyin the Elastic Beanstalk Developer Guide. For deploying a Ruby on Rails application with AWS OpsWorks, seeDeploying Ruby on

AWS SDK for Ruby Developer Guide, Release 1.0

Example

require 'aws-sdk'

# Uncomment for Windows.# Aws.use_bundled_cert!

cw = Aws::CloudWatch::Client.new(region: 'us-east-1')

# Send custom metrics to Amazon CloudWatch.# In this example, add metrics to the custom namespace "SITE/TRAFFIC":# For the custom dimension named "SiteName", for the value named "example.com→˓", add# "UniqueVisitors" of 5885 and "UniqueVisits" of 8628.# For the custom dimension named "PageURL", for the value named "my-page.html→˓", add# "PageViews" of 18057.cw.put_metric_data({

namespace: "SITE/TRAFFIC",metric_data: [

{metric_name: "UniqueVisitors",dimensions: [

{name: "SiteName",value: "example.com"

}],value: 5885.0,unit: "Count"

},{

metric_name: "UniqueVisits",dimensions: [

{name: "SiteName",value: "example.com"

}],value: 8628.0,unit: "Count"

},{

metric_name: "PageViews",dimensions: [

{name: "PageURL",value: "my-page.html"

}],value: 18057.0,unit: "Count"

}

5.1. Amazon CloudWatch Examples 29

Page 34: AWS SDK for Ruby Developer Guide … · Working with Rubyin the Elastic Beanstalk Developer Guide. For deploying a Ruby on Rails application with AWS OpsWorks, seeDeploying Ruby on

AWS SDK for Ruby Developer Guide, Release 1.0

]})

# Get information about custom metrics.list_metrics_output = cw.list_metrics({

namespace: "SITE/TRAFFIC"})

list_metrics_output.metrics.each do |metric|puts metric.metric_namemetric.dimensions.each do |dimension|puts "#{dimension.name} = #{dimension.value}"

endputs "\n"

end

5.1.5 Sending Events to Amazon CloudWatch Events

CloudWatch Events delivers a near real-time stream of system events that describe changes in AWSresources to AWS Lambda functions or other targets. To learn more, see What is Amazon CloudWatchEvents?. In this example, you use the AWS SDK for Ruby with CloudWatch Events to:

1. Create a rule in CloudWatch Events by using Aws::CloudWatchEvents::Client#put_rule.

2. Add a target to the rule by using Aws::CloudWatchEvents::Client#put_targets.

3. Send an event to CloudWatch Events so that it can be matched to the rule.

#. View the results in Amazon CloudWatch Logs and metrics by usingAws::CloudWatch::Client#get_metric_statistics and Aws::CloudWatchLogs::Client#describe_log_streams.

Prerequisites

Before running the example code, you need to install and configure the AWS SDK for Ruby, as describedin:

• Installing the AWS SDK for Ruby

• Configuring the AWS SDK for Ruby

You also need to:

• Replace the placeholder value assigned to lambda_function_arn with an actual Lambda functionARN.

1. Create a Lambda function, as described here.

2. Name the function LogEC2InstanceStateChange.

3. For a role, select Choose an Existing Role. For the existing role, selectlambda_basic_execution.

4. After you create the function, copy the ARN and paste it into your code.

30 Chapter 5. AWS SDK for Ruby Code Examples

Page 35: AWS SDK for Ruby Developer Guide … · Working with Rubyin the Elastic Beanstalk Developer Guide. For deploying a Ruby on Rails application with AWS OpsWorks, seeDeploying Ruby on

AWS SDK for Ruby Developer Guide, Release 1.0

• Replace the placeholder value assigned to cwe_service_role_arn with an appropriate AWS IAMservice role ARN.

1. In the IAM console, create a role and attach a policy that grants full access to CloudWatchEvents.

2. Ensure that the role has a trust relationship to events.amazonaws.com. For an example policyand role, see the comments in the example code on GitHub.

3. After you create the role, attach the policy, and establish the trust relationship, copy the roleARN and paste it into your code.

• Replace the placeholder value assigned to instance_id with an actual Amazon EC2 instance ID.

Example

require 'aws-sdk'

# Uncomment for Windows.# Aws.use_bundled_cert!

cwe = Aws::CloudWatchEvents::Client.new(region: 'us-east-1')

# Replace this value with the ARN of the AWS Lambda function you created→˓earlier.lambda_function_arn = "arn:aws:lambda:REGION-ID:ACCOUNT-ID:function:→˓LogEC2InstanceStateChange"

# Replace this value with the ARN of the AWS IAM service role you created→˓earlier.cwe_service_role_arn = "arn:aws:iam::ACCOUNT-ID:role/SERVICE-ROLE-NAME"

# Create a rule in Amazon CloudWatch Events.rule_name = "my-ec2-rule"

# The rule will use this pattern to route the event to the target.# This pattern is used whenever an Amazon EC2 instance begins running.event_pattern = {

"source" => ["aws.ec2"

],"detail-type" => [

"EC2 Instance State-change Notification"],"detail" => {

"state" => ["running"

]}

}.to_json

cwe.put_rule({name: rule_name,

5.1. Amazon CloudWatch Examples 31

Page 36: AWS SDK for Ruby Developer Guide … · Working with Rubyin the Elastic Beanstalk Developer Guide. For deploying a Ruby on Rails application with AWS OpsWorks, seeDeploying Ruby on

AWS SDK for Ruby Developer Guide, Release 1.0

event_pattern: event_pattern,state: "ENABLED",role_arn: cwe_service_role_arn

})

# Add a target to the rule.cwe.put_targets({

rule: rule_name,targets: [

{id: "my-rule-target",arn: lambda_function_arn

}]

})

# To test the rule, stop and then restart an existing Amazon EC2 instance.# For example:ec2 = Aws::EC2::Client.new(region: 'us-east-1')

# Replace this with an actual instance ID.instance_id = "i-INSTANCE-ID"

puts "Attempting to stop the instance. This may take a few minutes..."

ec2.stop_instances({instance_ids: [ instance_id ]

})

# Make sure the instance is stopped before attempting to restart it.ec2.wait_until(:instance_stopped, instance_ids: [ instance_id ])

puts "Attempt to restart the instance. This may take a few minutes..."

ec2.start_instances({instance_ids: [ instance_id ]

})

# Make sure the instance is running before continuing on.ec2.wait_until(:instance_running, instance_ids: [ instance_id ])

# See if and when the rule was triggered.cw = Aws::CloudWatch::Client.new(region: 'us-east-1')

invocations = cw.get_metric_statistics({namespace: "AWS/Events",metric_name: "Invocations",dimensions: [

{name: "RuleName",value: rule_name,

},],

32 Chapter 5. AWS SDK for Ruby Code Examples

Page 37: AWS SDK for Ruby Developer Guide … · Working with Rubyin the Elastic Beanstalk Developer Guide. For deploying a Ruby on Rails application with AWS OpsWorks, seeDeploying Ruby on

AWS SDK for Ruby Developer Guide, Release 1.0

start_time: Time.now - 600, # Look back over the past 10 minutes to see if→˓the rule was triggered (10 minutes * 60 seconds = 600 seconds).end_time: Time.now,period: 60, # Look back every 60 seconds over those past 10 minutes to see

→˓how many times the rule may have been triggered.statistics: [ "Sum" ],unit: "Count"

})

if invocations.datapoints.count > 0puts "Rule invocations:"invocations.datapoints.each do |datapoint|

puts " #{datapoint.sum} invocation(s) at #{datapoint.timestamp}"end

elseputs "No rule invocations."

end

# View the latest related log in Amazon CloudWatch Logs.cwl = Aws::CloudWatchLogs::Client.new(region: 'us-east-1')

describe_log_streams_response = cwl.describe_log_streams({log_group_name: "/aws/lambda/LogEC2InstanceStateChange",order_by: "LastEventTime",descending: true

})

get_log_events_response = cwl.get_log_events({log_group_name: "/aws/lambda/LogEC2InstanceStateChange",log_stream_name: describe_log_streams_response.log_streams[0].log_stream_

→˓name # Get the latest log stream only.})

puts "\nLog messages:\n\n"

get_log_events_response.events.each do |event|puts event.message

end

5.2 Amazon DynamoDB Examples

You can use the following examples to access Amazon DynamoDB services by using the AWS SDK forRuby. For more information about DynamoDB, see the Amazon DynamoDB documentation. Specifically,see Ruby and DynamoDB to learn how to:

• Create a table and load sample data in JSON format.

• Perform create, read, update, and delete operations on the table.

• Run simple queries.

5.2. Amazon DynamoDB Examples 33

Page 38: AWS SDK for Ruby Developer Guide … · Working with Rubyin the Elastic Beanstalk Developer Guide. For deploying a Ruby on Rails application with AWS OpsWorks, seeDeploying Ruby on

AWS SDK for Ruby Developer Guide, Release 1.0

The topic also provides a link to a downloadable version of DynamoDB, which includes an interactive webinterface so you can experiment with DynamoDB offline.

Examples

5.2.1 Getting Information about All Tables

The following example lists the names and number of items in each table in the us-west-2 region.

require 'aws-sdk'

dynamoDB = Aws::DynamoDB::Resource.new(region: 'us-west-2')

dynamoDB.tables.each do |t|puts "Name: #{t.name}"puts "#Items: #{t.item_count}"

end

5.2.2 Creating a Simple Table with a Single Primary Key

The following example creates the table Users with three attributes: ID, FirstName, and LastNamein the us-west-2 region.

The wait_until call blocks you from using the table until DynamoDB has created it. By default, theDynamoDB client’s wait_until method checks every 20 seconds, up to a maximum of 500 seconds, tosee if the table was created.

require 'aws-sdk'

attribute_defs = [{ attribute_name: 'ID', attribute_type: 'N' },{ attribute_name: 'FirstName', attribute_type: 'S' },{ attribute_name: 'LastName', attribute_type: 'S' }

]

key_schema = [{ attribute_name: 'ID', key_type: 'HASH' }

]

index_schema = [{ attribute_name: 'FirstName', key_type: 'HASH' },{ attribute_name: 'LastName', key_type: 'RANGE' }

]

global_indexes = [{index_name: 'LastNameFirstNameIndex',key_schema: index_schema,projection: { projection_type: 'ALL' },provisioned_throughput: { read_capacity_units: 5, write_capacity_units: 10 }

}]

34 Chapter 5. AWS SDK for Ruby Code Examples

Page 39: AWS SDK for Ruby Developer Guide … · Working with Rubyin the Elastic Beanstalk Developer Guide. For deploying a Ruby on Rails application with AWS OpsWorks, seeDeploying Ruby on

AWS SDK for Ruby Developer Guide, Release 1.0

request = {attribute_definitions: attribute_defs,table_name: 'Users',key_schema: key_schema,global_secondary_indexes: global_indexes,provisioned_throughput: { read_capacity_units: 5, write_capacity_units:

→˓10 }}

dynamodb_client = Aws::DynamoDB::Client.new(region: 'us-west-2')

dynamodb_client.create_table(request)dynamodb_client.wait_until(:table_exists, table_name: 'Users')

5.2.3 Adding an Item to a Table

The following example adds an item with the ID value of 123456, FirstName value of John, andLastName value of Doe to the Users table in the us-west-2 region.

require 'aws-sdk'

dynamoDB = Aws::DynamoDB::Resource.new(region: 'us-west-2')

table = dynamoDB.table('Users')

table.put_item({item:

{"ID" => 123456,"FirstName" => 'Snoop',"LastName" => 'Doug'

}})

5.2.4 Getting Information about the Items in a Table

The following example lists up to 50 items from the Users table in the us-west-2 region.

require 'aws-sdk'

dynamoDB = Aws::DynamoDB::Resource.new(region: 'us-west-2')

table = dynamoDB.table('Users')

scan_output = table.scan({limit: 50,select: "ALL_ATTRIBUTES"

})

scan_output.items.each do |item|keys = item.keys

5.2. Amazon DynamoDB Examples 35

Page 40: AWS SDK for Ruby Developer Guide … · Working with Rubyin the Elastic Beanstalk Developer Guide. For deploying a Ruby on Rails application with AWS OpsWorks, seeDeploying Ruby on

AWS SDK for Ruby Developer Guide, Release 1.0

keys.each do |k|puts "#{k}: #{item[k]}"

endend

5.2.5 Getting Information about a Specific Item in a Table

The following example displays the first and last name of an item with an ID of 123456 in the Users tablein the us-west-2 region.

require 'aws-sdk'

dynamoDB = Aws::DynamoDB::Resource.new(region: 'us-west-2')

table = dynamoDB.table('Users')

resp = table.get_item({key: { 'ID' => 123456 }

})

first_name = resp.item['FirstName']last_name = resp.item['LastName']

puts "First name: #{first_name}"puts "Last name: #{last_name}"

5.2.6 Updating a Table

The following example updates all the items in the Users table in the us-west-2 region to include anew field, airmiles, and sets the value to 10000.

require 'aws-sdk'

dynamoDB = Aws::DynamoDB::Resource.new(region: 'us-west-2')

table = dynamoDB.table('Users')

# Get the IDs of all of the usersresp = table.scan({ select: "ALL_ATTRIBUTES" })

resp.items.each do |item|id = item['ID']

request = {key: { 'ID' => id },update_expression: 'set airmiles=:pVal',expression_attribute_values: { ':pVal' => '10000' }

}

36 Chapter 5. AWS SDK for Ruby Code Examples

Page 41: AWS SDK for Ruby Developer Guide … · Working with Rubyin the Elastic Beanstalk Developer Guide. For deploying a Ruby on Rails application with AWS OpsWorks, seeDeploying Ruby on

AWS SDK for Ruby Developer Guide, Release 1.0

# Update the item in the table:table.update_item(request)

end

5.2.7 Creating an Index

The following example adds a new index, air-mileage-index, to the Users table in theus-west-2 region. Once the status of the index is ACTIVE, you can search for items in the table basedon the value of their airmiles.

require 'aws-sdk'

request = {attribute_definitions: [

{attribute_name: 'airmiles',attribute_type: 'N',

},],table_name: 'Users',global_secondary_index_updates: [

{create: {

index_name: 'air-mileage-index',key_schema: [{

attribute_name: 'airmiles',key_type: 'HASH',

},],projection: {

projection_type: 'ALL',},provisioned_throughput: {

read_capacity_units: 5,write_capacity_units: 10,

},},

},],

}

dynamoDB = Aws::DynamoDB::Client.new(region: 'us-west-2')

dynamoDB.update_table(request)

5.2. Amazon DynamoDB Examples 37

Page 42: AWS SDK for Ruby Developer Guide … · Working with Rubyin the Elastic Beanstalk Developer Guide. For deploying a Ruby on Rails application with AWS OpsWorks, seeDeploying Ruby on

AWS SDK for Ruby Developer Guide, Release 1.0

5.3 Amazon EC2 Examples

You can use the following examples to access Amazon Elastic Compute Cloud (Amazon EC2) using theAWS SDK for Ruby. For more information about Amazon EC2, see the Amazon EC2 Documentation.

Examples

5.3.1 Creating a VPC

The following example creates the virtual private cloud (VPC) MyGroovyVPC with the CIDR block10.200.0.0/16, and then displays the VPC’s ID.

The example creates a virtual network with 65,536 private IP addresses.

require 'aws-sdk'

ec2 = Aws::EC2::Resource.new(region: 'us-west-2')

vpc = ec2.create_vpc({ cidr_block: '10.200.0.0/16' })

# So we get a public DNSvpc.modify_attribute({

enable_dns_support: { value: true }})

vpc.modify_attribute({enable_dns_hostnames: { value: true }

})

# Name our VPCvpc.create_tags({ tags: [{ key: 'Name', value: 'MyGroovyVPC' }]})

puts vpc.vpc_id

5.3.2 Creating an Internet Gateway and Attaching It to a VPC

The following example creates an Internet gateway MyGroovyIGW, attaches it to a VPC that has IDVPC_ID, and then displays the Internet gateway’s ID.

require 'aws-sdk'

ec2 = Aws::EC2::Resource.new(region: 'us-west-2')

igw = ec2.create_internet_gateway

igw.create_tags({ tags: [{ key: 'Name', value: 'MyGroovyIGW' }]})igw.attach_to_vpc(vpc_id: VPC_ID)

puts igw.id

38 Chapter 5. AWS SDK for Ruby Code Examples

Page 43: AWS SDK for Ruby Developer Guide … · Working with Rubyin the Elastic Beanstalk Developer Guide. For deploying a Ruby on Rails application with AWS OpsWorks, seeDeploying Ruby on

AWS SDK for Ruby Developer Guide, Release 1.0

5.3.3 Creating a Public Subnet

The following example creates a public subnet MyGroovySubnet in the us-west-2 region and theAvailablity Zone us-west-2a. The example attaches the public subnet to a VPC with the ID VPC_IDthat uses the CIDR block 10.200.10.0/24, and then displays the subnet’s ID.

The public subnet created in this example has 256 private IP addresses within the VPC.

require 'aws-sdk'

ec2 = Aws::EC2::Resource.new(region: 'us-west-2')

subnet = ec2.create_subnet({vpc_id: VPC_ID,cidr_block: '10.200.10.0/24',availability_zone: 'us-west-2a'

})

subnet.create_tags({ tags: [{ key: 'Name', value: 'MyGroovySubnet' }]})puts subnet.id

5.3.4 Creating a Route Table and Associating It with a Subnet

The following example creates a route table MyGroovyRouteTable in us-west-2 region on a VPCwith the ID VPC_ID. The route table uses the route with the CIDR block 0.0.0.0/0 and the gatewaywith the ID IGW_ID. The example associates the route table with the subnet that has ID SUBNET_ID, andthen displays the route table’s ID.

require 'aws-sdk'

ec2 = Aws::EC2::Resource.new(region: 'us-west-2')

table = ec2.create_route_table({vpc_id: VPC_ID

})

table.create_tags({ tags: [{ key: 'Name', value: 'MyGroovyRouteTable' }]})

table.create_route({destination_cidr_block: '0.0.0.0/0',gateway_id: IGW_ID

})

table.associate_with_subnet({subnet_id: SUBNET_ID

})

puts table.id

5.3. Amazon EC2 Examples 39

Page 44: AWS SDK for Ruby Developer Guide … · Working with Rubyin the Elastic Beanstalk Developer Guide. For deploying a Ruby on Rails application with AWS OpsWorks, seeDeploying Ruby on

AWS SDK for Ruby Developer Guide, Release 1.0

5.3.5 Using Elastic IP Addresses in Amazon EC2

An Elastic IP address is a static IP address, designed for dynamic cloud computing, that is associated withyour AWS account. It’s a public IP address, which is reachable from the Internet. If your instance doesn’thave a public IP address, you can use an Elastic IP address with your instance so that it can communicatewith the Internet.

For more information about Elastic IP addresses in Amazon EC2, see Elastic IP Addresses in the AmazonEC2 User Guide for Linux Instances or Elastic IP Addresses in the Amazon EC2 User Guide for WindowsInstances.

In this example, you use the AWS SDK for Ruby with Amazon EC2 to:

1. Allocate an Elastic IP address by using the Aws::EC2::Client#allocate_address method.

2. Associate the address with an Amazon EC2 instance by using theAws::EC2::Client#associate_address method.

3. Get information about addresses associated with the instance by using theAws::EC2::Client#describe_addresses method.

4. Release the address by using the Aws::EC2::Client#release_address method.

The complete code for this example is available on GitHub.

Prerequisites

Before working with the example code, you need to install and configure the AWS SDK for Ruby, asdescribed in:

• Installing the AWS SDK for Ruby

• Configuring the AWS SDK for Ruby

You also need to launch an EC2 instance and note the instance ID.

Note: Before you run the following code, you must replace the INSTANCE-ID string with your actualinstance ID. This will be something like i-0a123456b7c8defg9.

Example Script

require 'aws-sdk'

ec2 = Aws::EC2::Client.new(region: 'us-east-1')

instance_id = "INSTANCE-ID" # For example, "i-0a123456b7c8defg9"

def display_addresses(ec2, instance_id)describe_addresses_result = ec2.describe_addresses({

filters: [

40 Chapter 5. AWS SDK for Ruby Code Examples

Page 45: AWS SDK for Ruby Developer Guide … · Working with Rubyin the Elastic Beanstalk Developer Guide. For deploying a Ruby on Rails application with AWS OpsWorks, seeDeploying Ruby on

AWS SDK for Ruby Developer Guide, Release 1.0

{name: "instance-id",values: [ instance_id ]

},]

})if describe_addresses_result.addresses.count == 0

puts "No addresses currently associated with the instance."else

describe_addresses_result.addresses.each do |address|puts "=" * 10puts "Allocation ID: #{address.allocation_id}"puts "Association ID: #{address.association_id}"puts "Instance ID: #{address.instance_id}"puts "Public IP: #{address.public_ip}"puts "Private IP Address: #{address.private_ip_address}"

endend

end

puts "Before allocating the address for the instance...."display_addresses(ec2, instance_id)

puts "\nAllocating the address for the instance..."allocate_address_result = ec2.allocate_address({

domain: "vpc"})

puts "\nAfter allocating the address for instance, but before associating the→˓address with the instance..."display_addresses(ec2, instance_id)

puts "\nAssociating the address with the instance..."associate_address_result = ec2.associate_address({

allocation_id: allocate_address_result.allocation_id,instance_id: instance_id,

})

puts "\nAfter associating the address with the instance, but before releasing→˓the address from the instance..."display_addresses(ec2, instance_id)

puts "\nReleasing the address from the instance..."ec2.release_address({

allocation_id: allocate_address_result.allocation_id,})

puts "\nAfter releasing the address from the instance..."display_addresses(ec2, instance_id)

5.3. Amazon EC2 Examples 41

Page 46: AWS SDK for Ruby Developer Guide … · Working with Rubyin the Elastic Beanstalk Developer Guide. For deploying a Ruby on Rails application with AWS OpsWorks, seeDeploying Ruby on

AWS SDK for Ruby Developer Guide, Release 1.0

5.3.6 Creating a Security Group

The following example creates a security group MyGroovySecurityGroup in the us-west-2 regionon a VPC with the ID VPC_ID. In the example, the security group is allowed access over port 22 (SSH)from all addresses (CIDR block 0.0.0.0/0) and is given the description “Security group forMyGroovyInstance”. Then, the security group’s ID is displayed.

require 'aws-sdk'

ec2 = Aws::EC2::Resource.new(region: 'us-west-2')

sg = ec2.create_security_group({group_name: 'MyGroovySecurityGroup',description: 'Security group for MyGroovyInstance',vpc_id: VPC_ID

})

sg.authorize_egress({ip_permissions: [{

ip_protocol: 'tcp',from_port: 22,to_port: 22,ip_ranges: [{

cidr_ip: '0.0.0.0/0'}]

})

puts sg.id

5.3.7 Working with Security Groups in Amazon EC2

An Amazon EC2 security group acts as a virtual firewall that controls the traffic for one or more instances.You add rules to each security group to allow traffic to or from its associated instances. You can modify therules for a security group at any time; the new rules are automatically applied to all instances that areassociated with the security group.

For more information about the Amazon EC2 security groups, see:

• Amazon EC2 Amazon Security Groups for Linux Instances

• Amazon EC2 Security Groups for Windows Instances

In this example, we use the AWS SDK for Ruby with Amazon EC2 to:

1. Create a security group.

2. Add rules to the security group.

3. Get information about security groups.

4. Delete the security group.

The full sample script containing all of the following examples is available on GitHub.

42 Chapter 5. AWS SDK for Ruby Code Examples

Page 47: AWS SDK for Ruby Developer Guide … · Working with Rubyin the Elastic Beanstalk Developer Guide. For deploying a Ruby on Rails application with AWS OpsWorks, seeDeploying Ruby on

AWS SDK for Ruby Developer Guide, Release 1.0

Prerequisites

Before working with the code below, you need to install and configure the AWS SDK for Ruby. See thefollowing:

• Installing the AWS SDK for Ruby

• Configuring the AWS SDK for Ruby

You’ll also need to create a VPC and note the VPC ID.

Configure the SDK

First we require the AWS SDK for Ruby and create an EC2 client. Then we provide a name for the securitygroup we’re going to create. We also need to provide the ID of our VPC, which is available in the consoleafter the VPC is created. Be sure that you replace ‘‘VPC-ID‘‘ with your actual VPC ID.

require 'aws-sdk'

ec2 = Aws::EC2::Client.new(region: 'us-east-1')

security_group_name = "my-security-group"vpc_id = "VPC-ID" # For example, "vpc-1234ab56".security_group_created = false # Used later to determine whether it's okay to→˓delete the security group.

We’ll use the security_group_created variable later in the script to determine if a security groupwas created and can therefore be deleted.

Create a Security Group

Next we create a security group that allows access over ports 22 (SSH) and 80 (HTTP) from all addresses(CIDR block 0.0.0.0/0).

# Create a security group.begin

create_security_group_result = ec2.create_security_group({group_name: security_group_name,description: "An example description for my security group.",vpc_id: vpc_id

})

# Add rules to the security group.# For example, allow all inbound HTTP and SSH traffic.ec2.authorize_security_group_ingress({

group_id: create_security_group_result.group_id,ip_permissions: [

{ip_protocol: "tcp",from_port: 80,to_port: 80,

5.3. Amazon EC2 Examples 43

Page 48: AWS SDK for Ruby Developer Guide … · Working with Rubyin the Elastic Beanstalk Developer Guide. For deploying a Ruby on Rails application with AWS OpsWorks, seeDeploying Ruby on

AWS SDK for Ruby Developer Guide, Release 1.0

ip_ranges: [{

cidr_ip: "0.0.0.0/0",}

]},{

ip_protocol: "tcp",from_port: 22,to_port: 22,ip_ranges: [

{cidr_ip: "0.0.0.0/0",

}]

}]

})

security_group_created = truerescue Aws::EC2::Errors::InvalidGroupDuplicate

puts "A security group with the name '#{security_group_name}' already→˓exists."end

If the begin block executes without exception, we set security_group_created to true.

Get Info about a Security Group

Having created a security group, we output information about our existing security groups and their IPpermissions.

def describe_ip_permission(ip_permission)puts "-" * 22puts "IP Protocol: #{ip_permission.ip_protocol}"puts "From Port: #{ip_permission.from_port.to_s}"puts "To Port: #{ip_permission.to_port.to_s}"if ip_permission.ip_ranges.count > 0

puts "IP Ranges:"ip_permission.ip_ranges.each do |ip_range|

puts " #{ip_range.cidr_ip}"end

endif ip_permission.ipv_6_ranges.count > 0

puts "IPv6 Ranges:"ip_permission.ipv_6_ranges.each do |ipv_6_range|

puts " #{ipv_6_range.cidr_ipv_6}"end

endif ip_permission.prefix_list_ids.count > 0

puts "Prefix List IDs:"ip_permission.prefix_list_ids.each do |prefix_list_id|

44 Chapter 5. AWS SDK for Ruby Code Examples

Page 49: AWS SDK for Ruby Developer Guide … · Working with Rubyin the Elastic Beanstalk Developer Guide. For deploying a Ruby on Rails application with AWS OpsWorks, seeDeploying Ruby on

AWS SDK for Ruby Developer Guide, Release 1.0

puts " #{prefix_list_id.prefix_list_id}"end

endif ip_permission.user_id_group_pairs.count > 0

puts "User ID Group Pairs:"ip_permission.user_id_group_pairs.each do |user_id_group_pair|

puts " ." * 7puts " Group ID: #{user_id_group_pair.group_id}"puts " Group Name: #{user_id_group_pair.group_name}"puts " Peering Status: #{user_id_group_pair.peering_status}"puts " User ID: #{user_id_group_pair.user_id}"puts " VPC ID: #{user_id_group_pair.vpc_id}"puts " VPC Peering Connection ID: #{user_id_group_pair.vpc_peering_

→˓connection_id}"end

endend

describe_security_groups_result = ec2.describe_security_groups

describe_security_groups_result.security_groups.each do |security_group|puts "\n"puts "*" * (security_group.group_name.length + 12)puts "Group Name: #{security_group.group_name}"puts "Group ID: #{security_group.group_id}"puts "Description: #{security_group.description}"puts "VPC ID: #{security_group.vpc_id}"puts "Owner ID: #{security_group.owner_id}"if security_group.ip_permissions.count > 0

puts "=" * 22puts "IP Permissions:"security_group.ip_permissions.each do |ip_permission|

describe_ip_permission(ip_permission)end

endif security_group.ip_permissions_egress.count > 0

puts "=" * 22puts "IP Permissions Egress:"security_group.ip_permissions_egress.each do |ip_permission|

describe_ip_permission(ip_permission)end

endif security_group.tags.count > 0

puts "=" * 22puts "Tags:"security_group.tags.each do |tag|puts " #{tag.key} = #{tag.value}"

endend

end

5.3. Amazon EC2 Examples 45

Page 50: AWS SDK for Ruby Developer Guide … · Working with Rubyin the Elastic Beanstalk Developer Guide. For deploying a Ruby on Rails application with AWS OpsWorks, seeDeploying Ruby on

AWS SDK for Ruby Developer Guide, Release 1.0

Delete a Security Group

At the end of the script, assuming that a security group was successfully created and thesecurity_group_created flag set to true, we delete the security group.

if security_group_createdec2.delete_security_group({ group_id: create_security_group_result.group_id

→˓})end

5.3.8 Working with Key Pairs

These examples show you how to use the AWS SDK for Ruby with Amazon EC2 to:

• Create a key pair.

• Get information about key pairs.

• Delete a key pair.

For more information about key pairs, see Amazon EC2 Key Pairs in the Amazon EC2 User Guide forLinux Instances or Amazon EC2 Key Pairs and Windows Instances in the Amazon EC2 User Guide forWindows Instances.

For additional code that you can use to run these examples, see Complete Example.

Create a Key Pair

Call the create_key_pair method, specifying the name of the key pair to create.

key_pair = ec2.create_key_pair({key_name: key_pair_name

})

In this code:

• ec2 is a variable representing an Aws::EC2::Client object.

• key_pair_name is a string variable representing the name of the key pair.

• key_pair is a variable representing an Aws::EC2::KeyPair object that is returned by calling thecreate_key_pair method.

For more information, see Complete Example.

Get Information about Key Pairs

To get information about a single key pair, use attributes such as:

• key_name, which gets the key pair’s name.

• key_fingerprint, which gets the SHA-1 digest of the DER encoded private key.

46 Chapter 5. AWS SDK for Ruby Code Examples

Page 51: AWS SDK for Ruby Developer Guide … · Working with Rubyin the Elastic Beanstalk Developer Guide. For deploying a Ruby on Rails application with AWS OpsWorks, seeDeploying Ruby on

AWS SDK for Ruby Developer Guide, Release 1.0

• key_material, which gets the unencrypted PEM encoded RSA private key.

puts "Created key pair '#{key_pair.key_name}'."puts "\nSHA-1 digest of the DER encoded private key:"puts "#{key_pair.key_fingerprint}"puts "\nUnencrypted PEM encoded RSA private key:"puts "#{key_pair.key_material}"

In this code, key_pair is a variable representing an Aws::EC2::KeyPair object, which is returned bycalling the create_key_pair method in the previous example.

To get information about multiple key pairs, call the describe_key_pairs method.

key_pairs_result = ec2.describe_key_pairs()

if key_pairs_result.key_pairs.count > 0puts "\nKey pair names:"key_pairs_result.key_pairs.each do |key_pair|

puts key_pair.key_nameend

end

In this code:

• ec2 is a variable representing an Aws::EC2::Client object.

• key_pair_result is a variable representing an Aws::EC2::Types::DescribeKeyPairsResultobject that is returned by calling the describe_key_pairs method.

• Calling the Aws::EC2::Types::DescribeKeyPairsResult object’s key_pairs methodreturns an array of Aws::EC2::Types::KeyPairInfo objects, which represent the key pairs.

For more information, see Complete Example.

Delete a Key Pair

Call the delete_key_pair method, specifying the name of the key pair to delete.

ec2.delete_key_pair({key_name: key_pair_name

})

In this code:

• ec2 is a variable representing an Aws::EC2::Client object.

• key_pair_name is a string variable representing the name of the key pair.

For more information, see Complete Example.

Complete Example

The following code, which you can adapt and run, combines the preceding examples into a single example.

5.3. Amazon EC2 Examples 47

Page 52: AWS SDK for Ruby Developer Guide … · Working with Rubyin the Elastic Beanstalk Developer Guide. For deploying a Ruby on Rails application with AWS OpsWorks, seeDeploying Ruby on

AWS SDK for Ruby Developer Guide, Release 1.0

require 'aws-sdk'

ec2 = Aws::EC2::Client.new(region: 'us-east-1')

key_pair_name = "my-key-pair"

# Create a key pair.begin

key_pair = ec2.create_key_pair({key_name: key_pair_name

})puts "Created key pair '#{key_pair.key_name}'."puts "\nSHA-1 digest of the DER encoded private key:"puts "#{key_pair.key_fingerprint}"puts "\nUnencrypted PEM encoded RSA private key:"puts "#{key_pair.key_material}"

rescue Aws::EC2::Errors::InvalidKeyPairDuplicateputs "A key pair named '#{key_pair_name}' already exists."

end

# Get information about Amazon EC2 key pairs.key_pairs_result = ec2.describe_key_pairs()

if key_pairs_result.key_pairs.count > 0puts "\nKey pair names:"key_pairs_result.key_pairs.each do |key_pair|

puts key_pair.key_nameend

end

# Delete the key pair.ec2.delete_key_pair({

key_name: key_pair_name})

To run this code, you must:

1. Install the AWS SDK for Ruby. For more information, see Installing the AWS SDK for Ruby.

2. Set the AWS access credentials that the AWS SDK for Ruby will use to verify your access to AWSservices and resources. For more information, see Configuring the AWS SDK for Ruby. Be sure theAWS credentials map to an AWS Identity and Access Management (IAM) entity with access to theAWS actions and resources described in this example. This example assumes you have set thecredentials in the AWS credentials profile file or in the AWS_ACCESS_KEY_ID andAWS_SECRET_ACCESS_KEY environment variables on your local system.

5.3.9 Getting Information about All Instances

The following example lists the IDs and states (pending, running, shutting down, terminated, stopping, orstopped) for all of your Amazon EC2 instances in the us-west-2 region.

48 Chapter 5. AWS SDK for Ruby Code Examples

Page 53: AWS SDK for Ruby Developer Guide … · Working with Rubyin the Elastic Beanstalk Developer Guide. For deploying a Ruby on Rails application with AWS OpsWorks, seeDeploying Ruby on

AWS SDK for Ruby Developer Guide, Release 1.0

require 'aws-sdk'

ec2 = Aws::EC2::Resource.new(region: 'us-west-2')

# To only get the first 10 instances:# ec2.instances.limit(10).each do |i|ec2.instances.each do |i|

puts "ID: #{i.id}"puts "State: #{i.state.name}"

end

5.3.10 Getting Information about All Instances with a Specific Tag Value

The following example lists the ID and state (pending, running, shutting down, terminated, stopping, orstopped) of an Amazon EC2 instance with the tag Group and tag value MyGroovyGroup in theus-west-2 region.

Note: The tag name and value are case-sensitive.

require 'aws-sdk'

ec2 = Aws::EC2::Resource.new(region: 'us-west-2')

# Get all instances with tag key 'Group'# and tag value 'MyGroovyGroup':ec2.instances({filters: [{name: 'tag:Group', values: ['MyGroovyGroup']}]}).→˓each do |i|puts 'ID: ' + i.idputs 'State: ' + i.state.name

end

5.3.11 Getting Information about a Specific Instance

The following example lists the state of an instance i-123abc in the us-west-2 region.

require 'aws-sdk'

ec2 = Aws::EC2::Resource.new(region: 'us-west-2')

i = ec2.instance('i-123abc')

if i.exists?puts "State: #{i.state.name}"

end

5.3. Amazon EC2 Examples 49

Page 54: AWS SDK for Ruby Developer Guide … · Working with Rubyin the Elastic Beanstalk Developer Guide. For deploying a Ruby on Rails application with AWS OpsWorks, seeDeploying Ruby on

AWS SDK for Ruby Developer Guide, Release 1.0

5.3.12 Creating an Instance

The following example creates an Amazon EC2 instance MyGroovyInstance, with the tag Group andvalue MyGroovyGroup. The instance is created in Availability Zone us-west-2a with the machineimage MACHINE_IMAGE for the account with ID ACCOUNT_ID, the security group with the IDSECURITY_GROUP_ID, and the subnet with the ID SUBNET_ID. Then, it displays the instance’s publicDNS and IP address.

Note: In the empty script value, you can add instructions that your Amazon EC2 instance executes when itstarts.

require 'aws-sdk'require 'base64'

# User code that's executed when the instance startsscript = ''

encoded_script = Base64.encode64(script)

ec2 = Aws::EC2::Resource.new(region: 'us-west-2')

instance = ec2.create_instances({image_id: 'IMAGE_ID',min_count: 1,max_count: 1,key_name: 'MyGroovyKeyPair',security_group_ids: ['SECURITY_GROUP_ID'],user_data: encoded_script,instance_type: 't2.micro',placement: {

availability_zone: 'us-west-2a'},subnet_id: 'SUBNET_ID',network_interfaces: [{

device_index: 0,associate_public_ip_address: true

}],iam_instance_profile: {

arn: 'arn:aws:iam::' + 'ACCOUNT_ID' + ':instance-profile/aws-opsworks-ec2-→˓role'}

})

# Wait for the instance to be created, running, and passed status checksec2.client.wait_until(:instance_status_ok, {instance_ids: [instance[0].id]})

# Name the instance 'MyGroovyInstance' and give it the Group tag→˓'MyGroovyGroup'instance.create_tags({ tags: [{ key: 'Name', value: 'MyGroovyInstance' }, {→˓key: 'Group', value: 'MyGroovyGroup' }]})

50 Chapter 5. AWS SDK for Ruby Code Examples

Page 55: AWS SDK for Ruby Developer Guide … · Working with Rubyin the Elastic Beanstalk Developer Guide. For deploying a Ruby on Rails application with AWS OpsWorks, seeDeploying Ruby on

AWS SDK for Ruby Developer Guide, Release 1.0

puts instance.id

5.3.13 Stopping an Instance

The following example stops the instance i-123abc in the us-west-2 region.

require 'aws-sdk'

ec2 = Aws::EC2::Resource.new(region: 'us-west-2')

i = ec2.instance('i-123abc')

if i.exists?case i.state.codewhen 48 # terminated

puts "#{id} is terminated, so you cannot stop it"when 64 # stoppingputs "#{id} is stopping, so it will be stopped in a bit"

when 89 # stoppedputs "#{id} is already stopped"

elsei.stop

endend

5.3.14 Starting an Instance

The following example starts the instance i-123abc in the us-west-2 region.

require 'aws-sdk'

ec2 = Aws::EC2::Resource.new(region: 'us-west-2')

i = ec2.instance('i-123abc')

if i.exists?case i.state.codewhen 0 # pending

puts "#{id} is pending, so it will be running in a bit"when 16 # startedputs "#{id} is already started"

when 48 # terminatedputs "#{id} is terminated, so you cannot start it"

elsei.start

endend

5.3. Amazon EC2 Examples 51

Page 56: AWS SDK for Ruby Developer Guide … · Working with Rubyin the Elastic Beanstalk Developer Guide. For deploying a Ruby on Rails application with AWS OpsWorks, seeDeploying Ruby on

AWS SDK for Ruby Developer Guide, Release 1.0

5.3.15 Rebooting an Instance

The following example reboots the instance i-123abc in the us-west-2 region.

require 'aws-sdk'

ec2 = Aws::EC2::Resource.new(region: 'us-west-2')

i = ec2.instance('i-123abc')

if i.exists?case i.state.codewhen 48 # terminated

puts "#{id} is terminated, so you cannot reboot it"else

i.rebootend

end

5.3.16 Managing Amazon EC2 Instances in Amazon EC2

In this example, you use the AWS SDK for Ruby with Amazon EC2 to:

1. Stop an existing Amazon EC2 instance by using Aws::EC2::Client#stop_instances.

2. Restart the instance by using Aws::EC2::Client#start_instances.

3. Reboot the instance by using Aws::EC2::Client#reboot_instances.

4. Enable detailed monitoring for the instance by using Aws::EC2::Client#monitor_instances.

5. Get information about available instances by using Aws::EC2::Client#describe_instances.

Prerequisites

Before running the example code, you need to install and configure the AWS SDK for Ruby, as describedin:

• Installing the AWS SDK for Ruby

• Configuring the AWS SDK for Ruby

You also need to replace INSTANCE-ID in the code with the instance ID of an existing EC2 instance.

Example

require 'aws-sdk'

# Uncomment for Windows.# Aws.use_bundled_cert!

52 Chapter 5. AWS SDK for Ruby Code Examples

Page 57: AWS SDK for Ruby Developer Guide … · Working with Rubyin the Elastic Beanstalk Developer Guide. For deploying a Ruby on Rails application with AWS OpsWorks, seeDeploying Ruby on

AWS SDK for Ruby Developer Guide, Release 1.0

def wait_for_instances(ec2, state, ids)begin

ec2.wait_until(state, instance_ids: ids)puts "Success: #{state}."

rescue Aws::Waiters::Errors::WaiterFailed => errorputs "Failed: #{error.message}"

endend

ec2 = Aws::EC2::Client.new(region: 'us-east-1')

instance_id = "INSTANCE-ID" # For example, "i-0a123456b7c8defg9"

puts "Attempting to stop instance '#{instance_id}'. This may take a few→˓minutes..."ec2.stop_instances({ instance_ids: [instance_id] })wait_for_instances(ec2, :instance_stopped, [instance_id])

puts "\nAttempting to restart instance '#{instance_id}'. This may take a few→˓minutes..."ec2.start_instances({ instance_ids: [instance_id] })wait_for_instances(ec2, :instance_running, [instance_id])

puts "\nAttempting to reboot instance '#{instance_id}'. This may take a few→˓minutes..."ec2.reboot_instances({ instance_ids: [instance_id] })wait_for_instances(ec2, :instance_status_ok, [instance_id])

# Enable detailed monitoring for the instance.puts "\nAttempting to enable detailed monitoring for instance '#{instance_id}→˓'..."

beginmonitor_instances_result = ec2.monitor_instances({

instance_ids: [instance_id]})puts "Detailed monitoring state for instance '#{instance_id}': #{monitor_

→˓instances_result.instance_monitorings[0].monitoring.state}"rescue Aws::EC2::Errors::InvalidState

puts "Instance '#{instance_id}' is not in a monitorable state. Continuing→˓on..."end

# Get information about available instances.puts "\nAvailable instances:"

describe_instances_result = ec2.describe_instances

describe_instances_result.reservations.each do |reservation|if reservation.instances.count > 0

reservation.instances.each do |instance|puts "=" * (instance.instance_id.length + 13)puts "Instance ID: #{instance.instance_id}"

5.3. Amazon EC2 Examples 53

Page 58: AWS SDK for Ruby Developer Guide … · Working with Rubyin the Elastic Beanstalk Developer Guide. For deploying a Ruby on Rails application with AWS OpsWorks, seeDeploying Ruby on

AWS SDK for Ruby Developer Guide, Release 1.0

puts "State: #{instance.state.name}"puts "Image ID: #{instance.image_id}"puts "Instance Type: #{instance.instance_type}"puts "Architecure: #{instance.architecture}"puts "IAM Instance Profile: #{instance.iam_instance_profile}"puts "Key Name: #{instance.key_name}"puts "Launch Time: #{instance.launch_time}"puts "Detailed Monitoring State: #{instance.monitoring.state}"puts "Public IP Address: #{instance.public_ip_address}"puts "Public DNS Name: #{instance.public_dns_name}"puts "VPC ID: #{instance.vpc_id}"puts "Subnet ID: #{instance.subnet_id}"if instance.tags.count > 0

puts "Tags:"instance.tags.each do |tag|

puts " #{tag.key} = #{tag.value}"end

endend

end

end

5.3.17 Terminating an Instance

The following example terminates the instance i-123abc in the us-west-2 region.

require 'aws-sdk'

ec2 = Aws::EC2::Resource.new(region: 'us-west-2')

i = ec2.instance('i-123abc')

if i.exists?case i.state.codewhen 48 # terminated

puts "#{id} is already terminated"else

i.terminateend

end

5.3.18 Getting Information about Regions and Availability Zones

These examples show you how to use the AWS SDK for Ruby together with Amazon EC2 to:

• Get information about available Amazon EC2 regions and their endpoints.

• Get information about available Amazon EC2 Availability Zones.

54 Chapter 5. AWS SDK for Ruby Code Examples

Page 59: AWS SDK for Ruby Developer Guide … · Working with Rubyin the Elastic Beanstalk Developer Guide. For deploying a Ruby on Rails application with AWS OpsWorks, seeDeploying Ruby on

AWS SDK for Ruby Developer Guide, Release 1.0

For more information about Amazon EC2 regions and Availability Zones, see Regions and AvailabilityZones in the Amazon EC2 User Guide for Linux Instances.

For additional code that you can use to run these examples, see Complete Example.

Get Information about Regions and Endpoints

Call the describe_regions method.

describe_regions_result = ec2.describe_regions()

In this code, ec2 is a variable representing an Aws::EC2::Client object. For more information, seeComplete Example.

1. Get an Aws::EC2::Types::DescribeRegionsResult object, which is returned by thedescribe_regions method and represented in this code by thedescribe_regions_result variable.

2. Use the DescribeRegionsResult object’s regions attribute to get an array ofAws::EC2::Types::Region objects representing the regions.

3. Get each region’s name and endpoint by using the Region object’s region_name and endpointattributes.

describe_regions_result.regions.each do |region|puts "#{region.region_name} (#{region.endpoint})"

end

Get Information about Availability Zones

Call the describe_availability_zones method.

describe_availability_zones_result = ec2.describe_availability_zones()

The Aws::EC2::Types::DescribeAvailabilityZonesResult object contains an array ofAws::EC2::Types::AvailabilityZone objects representing the Availability Zones. TheDescribeAvailabilityZonesResult object is returned by thedescribe_availability_zones method and represented in this code by thedescribe_availability_zones_result variable.

In this code, ec2 is a variable representing an Aws::EC2::Client object. For more information, seeComplete Example.

Use the AvailabilityZone object’s zone_name and state attributes.

describe_availability_zones_result.availability_zones.each do |zone|puts "#{zone.zone_name} is #{zone.state}"if zone.messages.count > 0

zone.messages.each do |message|" #{message.message}"

end

5.3. Amazon EC2 Examples 55

Page 60: AWS SDK for Ruby Developer Guide … · Working with Rubyin the Elastic Beanstalk Developer Guide. For deploying a Ruby on Rails application with AWS OpsWorks, seeDeploying Ruby on

AWS SDK for Ruby Developer Guide, Release 1.0

endend

1. Use the AvailabilityZone object’s messages attribute, which returns anAws::EC2::Types::AvailabilityZoneMessage array.

2. If there is at least one message in the array, use each AvailabilityZoneMessage object’smessage attribute to get the message.

Complete Example

The following code, which you can adapt and run, combines the preceding examples into a single example.

require 'aws-sdk'

ec2 = Aws::EC2::Client.new(region: 'us-east-1')

puts "Amazon EC2 region(s) (and their endpoint(s)) that are currently→˓available to you:\n\n"describe_regions_result = ec2.describe_regions()

describe_regions_result.regions.each do |region|puts "#{region.region_name} (#{region.endpoint})"

end

puts "\nAmazon EC2 availability zone(s) that are available to you for your→˓current region:\n\n"describe_availability_zones_result = ec2.describe_availability_zones()

describe_availability_zones_result.availability_zones.each do |zone|puts "#{zone.zone_name} is #{zone.state}"if zone.messages.count > 0

zone.messages.each do |message|" #{message.message}"

endend

end

1. Install the AWS SDK for Ruby. For more information, see Installing the AWS SDK for Ruby.

2. Set the AWS access credentials that the AWS SDK for Ruby will use to verify your access to AWSservices and resources. For more information, see Configuring the AWS SDK for Ruby. Be sure theAWS credentials map to an AWS Identity and Access Management (IAM) entity with access to theAWS actions and resources described in this example. This example assumes you have set thecredentials in the AWS credentials profile file or in the AWS_ACCESS_KEY_ID andAWS_SECRET_ACCESS_KEY environment variables on your local system.

56 Chapter 5. AWS SDK for Ruby Code Examples

Page 61: AWS SDK for Ruby Developer Guide … · Working with Rubyin the Elastic Beanstalk Developer Guide. For deploying a Ruby on Rails application with AWS OpsWorks, seeDeploying Ruby on

AWS SDK for Ruby Developer Guide, Release 1.0

5.4 AWS Elastic Beanstalk Examples

You can use the following examples to access AWS Elastic Beanstalk (Elastic Beanstalk) using the AWSSDK for Ruby. For more information about Elastic Beanstalk, see the Elastic Beanstalk Developer Guide.

Examples

5.4.1 Getting Information about All Applications

The following example lists the names, descriptions, and URLs of all of your Elastic Beanstalkapplications in the us-west-2 region.

require 'aws-sdk'

elb = Aws::ElasticBeanstalk::Client.new(region: 'us-west-2')

elb.describe_applications.applications.each do |a|puts "Name: #{a.application_name}"puts "Description: #{a.description}"

elb.describe_environments({application_name: a.application_name}).→˓environments.each do |env|

puts " Environment: #{env.environment_name}"puts " URL: #{env.cname}"puts " Health: #{env.health}"

endend

5.4.2 Getting Information about a Specific Application

The following example lists the name, description, and URL of the MyRailsApp application in theus-west-2 region.

require 'aws-sdk'

elb = Aws::ElasticBeanstalk::Client.new(region: 'us-west-2')

app = elb.describe_applications({application_names: [args[0]]})

if app.exists?puts "Name: #{app.application_name}"puts "Description: #{app.description}"

envs = elb.describe_environments({application_name: app.application_name})puts "URL: #{envs.environments[0].cname}"

end

5.4. AWS Elastic Beanstalk Examples 57

Page 62: AWS SDK for Ruby Developer Guide … · Working with Rubyin the Elastic Beanstalk Developer Guide. For deploying a Ruby on Rails application with AWS OpsWorks, seeDeploying Ruby on

AWS SDK for Ruby Developer Guide, Release 1.0

5.4.3 Updating a Ruby on Rails Application

The following example updates the Ruby on Rails application MyRailsApp in the us-west-2 region.

Note: You must be in the root of your Rails app to succesfully run the script.

require 'aws-sdk'

Aws.config.update({region: 'us-west-2'})

elb = Aws::ElasticBeanstalk::Client.news3 = Aws::S3::Client.new

app_name = 'MyRailsApp'

# Get S3 bucket containing appapp_versions = elb.describe_application_versions({ application_name: app_name→˓})av = app_versions.application_versions[0]bucket = av.source_bundle.s3_buckets3_key = av.source_bundle.s3_key

# Get info on environmentenvs = elb.describe_environments({ application_name: app_name })env = envs.environments[0]env_name = env.environment_name

# Create new storage locationresp = elb.create_storage_location()

puts "Created storage location in bucket #{resp.s3_bucket}"

resp = s3.list_objects({prefix: s3_key,bucket: bucket

})

# Create ZIP filezip_file_basename = SecureRandom.urlsafe_base64.to_szip_file_name = zip_file_basename + '.zip'

# Call out to OS to produce ZIP filecmd = "git archive --format=zip -o #{zip_file_name} HEAD"%x[ #{cmd} ]

# Get ZIP file contentszip_contents = File.read(zip_file_name)

key = app_name + "\\" + zip_file_name

resp = s3.put_object({

58 Chapter 5. AWS SDK for Ruby Code Examples

Page 63: AWS SDK for Ruby Developer Guide … · Working with Rubyin the Elastic Beanstalk Developer Guide. For deploying a Ruby on Rails application with AWS OpsWorks, seeDeploying Ruby on

AWS SDK for Ruby Developer Guide, Release 1.0

body: zip_contents,bucket: bucket,key: key

})

date = Time.newtoday = date.day.to_s + "/" + date.month.to_s + "/" + date.year.to_s

elb.create_application_version({process: false,application_name: app_name,version_label: zip_file_basename,source_bundle: {

s3_bucket: bucket,s3_key: key

},description: "Updated #{today}"

})

elb.update_environment({environment_name: env_name,version_label: zip_file_basename

})

5.5 AWS Identity and Access Management Examples

You can use the following examples to access AWS Identity and Access Management (IAM) using theAWS SDK for Ruby. For more information about IAM, see the IAM documentation.

Examples

5.5.1 Getting Information about All Users

The following example lists the groups, policies, and access key IDs of all IAM users in the us-west-2region.

require 'aws-sdk'

iam = Aws::IAM::Client.new(region: 'us-west-2')

iam.list_users.users.each do |user|name = user.user_nameputs "For user #{name}"puts " In groups:"

iam.list_groups_for_user({user_name: name}).groups.each do |group|puts " #{group.group_name}"

end

5.5. AWS Identity and Access Management Examples 59

Page 64: AWS SDK for Ruby Developer Guide … · Working with Rubyin the Elastic Beanstalk Developer Guide. For deploying a Ruby on Rails application with AWS OpsWorks, seeDeploying Ruby on

AWS SDK for Ruby Developer Guide, Release 1.0

puts " Policies:"

iam.list_user_policies({user_name: name}).policy_names.each do |policy|puts " #{policy}"

end

puts " Access keys:"

iam.list_access_keys({user_name: name}).access_key_metadata.each do |key|puts " #{key.access_key_id}"

endend

5.5.2 Adding a New User

The following example creates the IAM |user my_groovy_user in the us-west-2 region with thepassword REPLACE_ME, and displays the user’s account ID. If a user with that name already exists, itdisplays a message and does not create a new user.

require 'aws-sdk'

iam = Aws::IAM::Client.new(region: 'us-west-2')

beginuser = iam.create_user(user_name: 'my_groovy_user')iam.wait_until(:user_exists, user_name: 'my_groovy_user')

user.create_login_profile({password: 'REPLACE_ME'})

arn_parts = user.arn.split(':')puts 'Account ID: ' + arn_parts[4]

rescue Aws::IAM::Errors::EntityAlreadyExistsputs 'User already exists'

end

5.5.3 Create a User’s Access Keys

The following example creates an access key and secret key for the IAM user my_groovy_user in the:code-:us-west-2 region.

require 'aws-sdk'

iam = Aws::IAM::Client.new(region: 'us-west-2')

beginuser = iam.user(user_name: 'my_groovy_user')

key_pair = user.create_access_key_pair

60 Chapter 5. AWS SDK for Ruby Code Examples

Page 65: AWS SDK for Ruby Developer Guide … · Working with Rubyin the Elastic Beanstalk Developer Guide. For deploying a Ruby on Rails application with AWS OpsWorks, seeDeploying Ruby on

AWS SDK for Ruby Developer Guide, Release 1.0

puts "Access key: #{key_pair.access_key_id}"puts "Secret key: #{key_pair.secret}"

rescue Aws::IAM::Errors::NoSuchEntity => exputs 'User does not exist'

end

5.5.4 Adding a Managed Policy

The following example adds the managed policy AmazonS3FullAccess to the IAM usermy_groovy_user in the us-west-2 region.

require 'aws-sdk'

# Policy ARNs start with:prefix = 'arn:aws:iam::aws:policy/'

policy_arn = prefix + 'AmazonS3FullAccess'

# In case the policy or user does not existbegin

client.attach_user_policy({user_name: 'my_groovy_user', policy_arn: policy_→˓arn})rescue Aws::IAM::Errors::NoSuchEntity => ex

puts "Error attaching policy '#{policy_arn}'"puts ex.message

end

5.5.5 Creating a Role

The following example creates the role my_groovy_role so that Amazon EC2 can access Amazon S3and Amazon DynamoDB in the us-west-2 region.

require 'aws-sdk'

client = Aws::IAM::Client.new(region: 'us-west-2')iam = Aws::IAM::Resource.new(client: client)

# Let EC2 assume a rolepolicy_doc = {

Version:"2012-10-17",Statement:[

{Effect:"Allow",Principal:{

Service:"ec2.amazonaws.com"},Action:"sts:AssumeRole"

}]}

5.5. AWS Identity and Access Management Examples 61

Page 66: AWS SDK for Ruby Developer Guide … · Working with Rubyin the Elastic Beanstalk Developer Guide. For deploying a Ruby on Rails application with AWS OpsWorks, seeDeploying Ruby on

AWS SDK for Ruby Developer Guide, Release 1.0

role = iam.create_role({role_name: 'my_groovy_role',assume_role_policy_document: policy_doc.to_json

})

# Give the role full access to S3role.attach_policy({

policy_arn: 'arn:aws:iam::aws:policy/AmazonS3FullAccess'})

# Give the role full access to DynamoDBrole.attach_policy({

policy_arn: 'arn:aws:iam::aws:policy/AmazonDynamoDBFullAccess'})

5.5.6 Managing IAM Users

An IAM user represents a person or service that interacts with AWS. For more information about IAMusers, see IAM Users.

In this example, you use the AWS SDK for Ruby with IAM to:

1. Get information about available AWS IAM users by using Aws::IAM::Client#list_users.

2. Create a user by using Aws::IAM::Client#create_user.

3. Update the user’s name by using Aws::IAM::Client#update_user.

4. Delete the user by using Aws::IAM::Client#delete_user.

Prerequisites

Before running the example code, you need to install and configure the AWS SDK for Ruby, as describedin:

• Installing the AWS SDK for Ruby

• Configuring the AWS SDK for Ruby

Example

require 'aws-sdk'

iam = Aws::IAM::Client.new(region: 'us-east-1')

user_name = "my-user"changed_user_name = "my-changed-user"

# Get information about available AWS IAM users.

62 Chapter 5. AWS SDK for Ruby Code Examples

Page 67: AWS SDK for Ruby Developer Guide … · Working with Rubyin the Elastic Beanstalk Developer Guide. For deploying a Ruby on Rails application with AWS OpsWorks, seeDeploying Ruby on

AWS SDK for Ruby Developer Guide, Release 1.0

def list_user_names(iam)list_users_response = iam.list_userslist_users_response.users.each do |user|

puts user.user_nameend

end

puts "User names before creating user..."list_user_names(iam)

# Create a user.puts "\nCreating user..."

iam.create_user({ user_name: user_name })

puts "\nUser names after creating user..."list_user_names(iam)

# Update the user's name.puts "\nChanging user's name..."

beginiam.update_user({

user_name: user_name,new_user_name: changed_user_name

})

puts "\nUser names after updating user's name..."list_user_names(iam)

rescue Aws::IAM::Errors::EntityAlreadyExistsputs "User '#{user_name}' already exists."

end

# Delete the user.puts "\nDeleting user..."iam.delete_user({ user_name: changed_user_name })

puts "\nUser names after deleting user..."list_user_names(iam)

5.5.7 Working with IAM Policies

An IAM policy is a document that specifies one or more permissions. For more information about IAMpolicies, see Overview of IAM Policies.

In this example, you use the AWS SDK for Ruby with IAM to:

1. Create a policy, using Aws::IAM::Client#create_policy.

2. Get information about the policy, using Aws::IAM::Client#get_policy.

3. Attach the policy to a role, using Aws::IAM::Client#attach_role_policy.

5.5. AWS Identity and Access Management Examples 63

Page 68: AWS SDK for Ruby Developer Guide … · Working with Rubyin the Elastic Beanstalk Developer Guide. For deploying a Ruby on Rails application with AWS OpsWorks, seeDeploying Ruby on

AWS SDK for Ruby Developer Guide, Release 1.0

4. List policies attached to the role, using Aws::IAM::Client#list_attached_role_policies.

5. Detach the policy from the role, using Aws::IAM::Client#detach_role_policy.

Prerequisites

Before running the example code, you need to install and configure the AWS SDK for Ruby, as describedin:

• Installing the AWS SDK for Ruby

• Configuring the AWS SDK for Ruby

You will also need to create the role (my-role) specified in the script. You can do this in the IAM console.

Example

require 'aws-sdk'

iam = Aws::IAM::Client.new(region: 'us-east-1')

role_name = "my-role"policy_name = "my-policy"policy_document = {

"Version" => "2012-10-17","Statement" => [

{"Effect" => "Allow","Action" => "s3:ListAllMyBuckets","Resource" => "arn:aws:s3:::*"

}]

}.to_json

# Create a policy.puts "Creating policy..."

create_policy_response = iam.create_policy({policy_name: policy_name,policy_document: policy_document

})

policy_arn = create_policy_response.policy.arn

# Get information about the policy.get_policy_response = iam.get_policy({ policy_arn: policy_arn })

puts "\nCreated policy, ID = #{get_policy_response.policy.policy_id}"

# Attach the policy to a role.puts "\nAttaching policy to role..."

64 Chapter 5. AWS SDK for Ruby Code Examples

Page 69: AWS SDK for Ruby Developer Guide … · Working with Rubyin the Elastic Beanstalk Developer Guide. For deploying a Ruby on Rails application with AWS OpsWorks, seeDeploying Ruby on

AWS SDK for Ruby Developer Guide, Release 1.0

iam.attach_role_policy({role_name: role_name,policy_arn: policy_arn

})

# List policies attached to the role.puts "\nAttached role policy ARNs..."

iam.list_attached_role_policies({ role_name: role_name }).attached_policies.→˓each do |attached_policy|puts " #{attached_policy.policy_arn}"

end

# Detach the policy from the role.puts "\nDetaching role policy..."

iam.detach_role_policy({role_name: role_name,policy_arn: policy_arn

})

5.5.8 Managing IAM Access Keys

Users need their own access keys to make programmatic calls to AWS from the SDK for Ruby. To fill thisneed, you can create, modify, view, or rotate access keys (access key IDs and secret access keys) for IAMusers. By default, when you create an access key, its status is Active, which means the user can use theaccess key for API calls. For more information about access keys, see Managing Access Keys for IAMUsers.

In this example, you use the AWS SDK for Ruby with IAM to:

1. List AWS IAM user access keys, using Aws::IAM::Client#list_access_keys.

2. Create an access key, using Aws::IAM::Client#create_access_key.

3. Determine when access keys were last used, using Aws::IAM::Client#get_access_key_last_used.

4. Deactivate access keys, using Aws::IAM::Client#update_access_key.

5. Delete the access key, using Aws::IAM::Client#delete_access_key.

Prerequisites

Before running the example code, you need to install and configure the AWS SDK for Ruby, as describedin:

• Installing the AWS SDK for Ruby

• Configuring the AWS SDK for Ruby

You will also need to create the user (my-user) specified in the script. You can create a new IAM user in theIAM console or programmatically, as shown at Adding a New User.

5.5. AWS Identity and Access Management Examples 65

Page 70: AWS SDK for Ruby Developer Guide … · Working with Rubyin the Elastic Beanstalk Developer Guide. For deploying a Ruby on Rails application with AWS OpsWorks, seeDeploying Ruby on

AWS SDK for Ruby Developer Guide, Release 1.0

Example

require 'aws-sdk'

iam = Aws::IAM::Client.new(region: 'us-east-1')

user_name = "my-user"

# List user access keys.def list_keys(iam, user_name)

beginlist_access_keys_response = iam.list_access_keys({ user_name: user_name })

if list_access_keys_response.access_key_metadata.count == 0puts "No access keys."

elseputs "Access keys:"list_access_keys_response.access_key_metadata.each do |key_metadata|

puts " Access key ID: #{key_metadata.access_key_id}"end

end

rescue Aws::IAM::Errors::NoSuchEntityputs "Cannot find user '#{user_name}'."exit(false)

endend

puts "Before creating access key..."list_keys(iam, user_name)

# Create an access key.puts "\nCreating access key..."

beginiam.create_access_key({ user_name: user_name })puts "\nAfter creating access key..."list_keys(iam, user_name)

rescue Aws::IAM::Errors::LimitExceededputs "Too many access keys. Can't create any more."

end

# Determine when access keys were last used.puts "\nKey(s) were last used..."

list_access_keys_response = iam.list_access_keys({ user_name: user_name })

list_access_keys_response.access_key_metadata.each do |key_metadata|resp = iam.get_access_key_last_used({ access_key_id: key_metadata.access_

→˓key_id })

puts " Key '#{key_metadata.access_key_id}' last used on #{resp.access_key_→˓last_used.last_used_date}"

66 Chapter 5. AWS SDK for Ruby Code Examples

Page 71: AWS SDK for Ruby Developer Guide … · Working with Rubyin the Elastic Beanstalk Developer Guide. For deploying a Ruby on Rails application with AWS OpsWorks, seeDeploying Ruby on

AWS SDK for Ruby Developer Guide, Release 1.0

# Deactivate access keys.puts " Trying to deactivate this key..."

iam.update_access_key({user_name: user_name,access_key_id: key_metadata.access_key_id,status: "Inactive"

})end

puts "\nAfter deactivating access key(s)..."list_keys(iam, user_name)

# Delete the access key.puts "\nDeleting access key..."

iam.delete_access_key({user_name: user_name,access_key_id: list_access_keys_response.access_key_metadata[0].access_key_

→˓id})

puts "\nAfter deleting access key..."list_keys(iam, user_name)

5.5.9 Working with IAM Server Certificates

To enable HTTPS connections to your website or application on AWS, you need an SSL/TLS servercertificate. To use a certificate that you obtained from an external provider with your website or applicationon AWS, you must upload the certificate to IAM or import it into AWS Certificate Manager. For moreinformation about server certificates, see Working with Server Certificates.

In this example, you use the AWS SDK for Ruby with IAM to:

1. Update a server certificate, using Aws::IAM::Client#update_server_certificate.

2. Delete the server certificate, using Aws::IAM::Client#delete_server_certificate.

3. List information about any remaining server certificates, usingAws::IAM::Client#list_server_certificates.

Prerequisites

Before running the example code, you need to install and configure the AWS SDK for Ruby, as describedin:

• Installing the AWS SDK for Ruby

• Configuring the AWS SDK for Ruby

5.5. AWS Identity and Access Management Examples 67

Page 72: AWS SDK for Ruby Developer Guide … · Working with Rubyin the Elastic Beanstalk Developer Guide. For deploying a Ruby on Rails application with AWS OpsWorks, seeDeploying Ruby on

AWS SDK for Ruby Developer Guide, Release 1.0

Note also that the server certificate must already exist, or the script will throw anAws::IAM::Errors::NoSuchEntity error.

Example

require 'aws-sdk'

iam = Aws::IAM::Client.new(region: 'us-east-1')

server_certificate_name = "my-server-certificate"changed_server_certificate_name = "my-changed-server-certificate"

# Update a server certificate.iam.update_server_certificate({

server_certificate_name: server_certificate_name,new_server_certificate_name: changed_server_certificate_name

})

# Delete the server certificate.iam.delete_server_certificate({

server_certificate_name: changed_server_certificate_name})

# List information about any remaining server certificates.list_server_certificates_response = iam.list_server_certificates

if list_server_certificates_response.server_certificate_metadata_list.count→˓== 0puts "No server certificates."

elselist_server_certificates_response.server_certificate_metadata_list.each do

→˓|certificate_metadata|puts "-" * certificate_metadata.server_certificate_name.lengthputs "Name: #{certificate_metadata.server_certificate_name}"

get_server_certificate_response = iam.get_server_certificate({server_certificate_name: "certificate_metadata.server_certificate_name"

})puts "ID: #{get_server_certificate_response.server_certificate.server_

→˓certificate_metadata.server_certificate_id}"end

end

5.5.10 Managing IAM Account Aliases

If you want the URL for your sign-in page to contain your company name or other friendly identifierinstead of your AWS account ID, you can create an alias for your AWS account ID. If you create an AWSaccount alias, your sign-in page URL changes to incorporate the alias. For more information about IAMaccount aliases, see Your AWS Account ID and Its Alias.

68 Chapter 5. AWS SDK for Ruby Code Examples

Page 73: AWS SDK for Ruby Developer Guide … · Working with Rubyin the Elastic Beanstalk Developer Guide. For deploying a Ruby on Rails application with AWS OpsWorks, seeDeploying Ruby on

AWS SDK for Ruby Developer Guide, Release 1.0

In this example, you use the AWS SDK for Ruby with IAM to:

1. List AWS account aliases, using Aws::IAM::Client#list_account_aliases.

2. Create an account alias, using Aws::IAM::Client#create_account_alias.

3. Delete the account alias, using Aws::IAM::Client#delete_account_alias.

Prerequisites

Before running the example code, you need to install and configure the AWS SDK for Ruby, as describedin:

• Installing the AWS SDK for Ruby

• Configuring the AWS SDK for Ruby

In the example code, change the my-account-alias string to something that will be unique across allAmazon Web Services products.

Example

require 'aws-sdk'

iam = Aws::IAM::Client.new(region: 'us-east-1')

account_alias = "my-account-alias"

# List account aliases.def list_aliases(iam)

list_account_aliases_response = iam.list_account_aliases

if list_account_aliases_response.account_aliases.count == 0puts "No account aliases."

elseputs "Aliases:"list_account_aliases_response.account_aliases.each do |account_alias|

puts account_aliasend

end

end

puts "Before creating account alias..."list_aliases(iam)

# Create an account alias.puts "\nCreating account alias..."iam.create_account_alias({ account_alias: account_alias })

puts "\nAfter creating account alias..."list_aliases(iam)

5.5. AWS Identity and Access Management Examples 69

Page 74: AWS SDK for Ruby Developer Guide … · Working with Rubyin the Elastic Beanstalk Developer Guide. For deploying a Ruby on Rails application with AWS OpsWorks, seeDeploying Ruby on

AWS SDK for Ruby Developer Guide, Release 1.0

# Delete the account alias.puts "\nDeleting account alias..."iam.delete_account_alias({ account_alias: account_alias })

puts "\nAfter deleting account alias..."list_aliases(iam)

5.6 Lambda Examples

You can use the following examples to access AWS Lambda (Lambda) using the AWS SDK for Ruby. Formore information about Lambda, see the Lambda documentation.

Examples

5.6.1 Displaying Information about All Lambda Functions

The following example displays the name, ARN, and role of all of your Lambda functions in theus-west-2 region.

require 'aws-sdk'

client = Aws::Lambda::Client.new(region: 'us-west-2')

client.list_functions.each do |function|puts 'Name: ' + function.function_nameputs 'ARN: ' + function.function_arnputs 'Role: ' + function.role

5.6.2 Creating a Lambda Function

The following example creates the Lambda function my-notification-function in theus-west-2 region using these values:

• Role ARN: my-resource-arn. In most cases, you need to attach only theAWSLambdaExecute managed policy to the policy for this role.

• Function entry point: my-package.my-class

• Runtime: java8

• Zip file: my-zip-file.zip

• Bucket: my-notification-bucket

• Key: my-zip-file

70 Chapter 5. AWS SDK for Ruby Code Examples

Page 75: AWS SDK for Ruby Developer Guide … · Working with Rubyin the Elastic Beanstalk Developer Guide. For deploying a Ruby on Rails application with AWS OpsWorks, seeDeploying Ruby on

AWS SDK for Ruby Developer Guide, Release 1.0

require 'aws-sdk'

client = Aws::Lambda::Client.new(region: 'us-west-2')

args = {}args[:role] = 'my-resource-arn'args[:function_name] = 'my-notification-function'args[:handler] = 'my-package.my-class'

# Also accepts nodejs, nodejs4.3, and python2.7args[:runtime] = 'java8'

code = {}code[:zip_file] = 'my-zip-file.zip'code[:s3_bucket] = 'my-notification-bucket'code[:s3_key] = 'my-zip-file'

args[:code] = code

client.create_function(args)

5.6.3 Configuring a Lambda Function to Receive Notifications

The following example configures the Lambda function my-notification-function in theus-west-2 region to accept notifications from the resource with the ARN my-resource-arn.

require 'aws-sdk'

client = Aws::Lambda::Client.new(region: 'us-west-2')

args = {}args[:function_name] = 'my-notification-function'args[:statement_id] = 'lambda_s3_notification'args[:action] = 'lambda:InvokeFunction'args[:principal] = 's3.amazonaws.com'args[:source_arn] = 'my-resource-arn'

client.add_permission{args]

5.7 Amazon Relational Database Service Examples

You can use the following examples to access Amazon Relational Database Service (Amazon RDS) usingthe AWS SDK for Ruby. For more information about Amazon RDS, see the Amazon Relational DatbaseService User Guide.

Note: Some of the following examples use methods that were introduced in the 2.2.18 version of theAws::RDS::Resource class. To run those examples, you must use that version or a later version of the

5.7. Amazon Relational Database Service Examples 71

Page 76: AWS SDK for Ruby Developer Guide … · Working with Rubyin the Elastic Beanstalk Developer Guide. For deploying a Ruby on Rails application with AWS OpsWorks, seeDeploying Ruby on

AWS SDK for Ruby Developer Guide, Release 1.0

aws-sdk gem.

Examples

5.7.1 Getting Information about All Instances

The following example lists the name (ID) and status of all of your Amazon RDS instances in theus-west-2 region.

require 'aws-sdk'

rds = Aws::RDS::Resource.new(region: 'us-west-2')

rds.db_instances.each do |i|puts "Name (ID): #{i.id}"puts "Status : #{i.db_instance_status}"puts

end

5.7.2 Getting Information about All Snapshots

The following example lists the names (IDs) and status of all of your Amazon RDS (instance) snapshots inthe us-west-2 region.

require 'aws-sdk'

rds = Aws::RDS::Resource.new(region: 'us-west-2')

rds.db_snapshots.each do |s|puts "Name (ID): #{s.snapshot_id}"puts "Status: #{s.status}"

end

5.7.3 Getting Information about All Clusters and Their Snapshots

The following example lists the name (ID) and status of all of your Amazon RDS clusters and the name(ID) and status of their snapshots in the us-west-2 region.

require 'aws-sdk'

rds = Aws::RDS::Resource.new(region: 'us-west-2')

rds.db_clusters.each do |c|puts "Name (ID): #{c.id}"puts "Status: #{c.status}"

c.snapshots.each do |s|puts " Snapshot: #{s.snapshot_id}"

72 Chapter 5. AWS SDK for Ruby Code Examples

Page 77: AWS SDK for Ruby Developer Guide … · Working with Rubyin the Elastic Beanstalk Developer Guide. For deploying a Ruby on Rails application with AWS OpsWorks, seeDeploying Ruby on

AWS SDK for Ruby Developer Guide, Release 1.0

puts " Status: #{s.status}"end

end

5.7.4 Getting Information about All Security Groups

The following example lists the names of all of your Amazon RDS security groups in the us-west-2region.

Note: Amazon RDS security groups are only applicable when you are using the Amazon EC2 classicplatform. If you are using Amazon EC2 VPC, use VPC security groups. Both are shown in the example.

require 'aws-sdk'

rds = Aws::RDS::Resource.new(region: 'us-west-2')

rds.db_instances.each do |i|# Show any security group IDs and descriptionsputs 'Security Groups:'

i.db_security_groups.each do |sg|puts sg.db_security_group_nameputs ' ' + sg.db_security_group_descriptionputs

end

# Show any VPC security group IDs and their statusputs 'VPC Security Groups:'

i.vpc_security_groups.each do |vsg|puts vsg.vpc_security_group_idputs ' ' + vsg.statusputs

endend

5.7.5 Getting Information about All Subnet Groups

The following example lists the name and status of all of your Amazon RDS subnet groups in theus-west-2 region.

require 'aws-sdk'

rds = Aws::RDS::Resource.new(region: 'us-west-2')

rds.db_subnet_groups.each do |s|puts s.name

5.7. Amazon Relational Database Service Examples 73

Page 78: AWS SDK for Ruby Developer Guide … · Working with Rubyin the Elastic Beanstalk Developer Guide. For deploying a Ruby on Rails application with AWS OpsWorks, seeDeploying Ruby on

AWS SDK for Ruby Developer Guide, Release 1.0

puts ' ' + s.subnet_group_statusend

5.7.6 Getting Information about All Parameter Groups

The following example lists the names and descriptions of all of your Amazon RDS parameter groups inthe us-west-2 region.

require 'aws-sdk'

rds = Aws::RDS::Resource.new(region: 'us-west-2')

rds.db_parameter_groups.each do |p|puts p.db_parameter_group_nameputs ' ' + p.description

end

5.7.7 Creating a Snapshot of an Instance

The following example creates a snapshot for the Amazon RDS instance represented by instance_name inthe us-west-2 region.

Note: If your instance is a member of a cluster, you can’t create a snapshot of the instance, but insteadmust create a snapshot of the cluster (see Creating a Snapshot of a Cluster).

require 'aws-sdk'

rds = Aws::RDS::Resource.new(region: 'us-west-2')

instance = rds.db_instance(instance_name)

date = Time.newdate_time = date.year.to_s + '-' + date.month.to_s + '-' + date.day.to_s→˓+ '-' + date.hour.to_s + '-' + date.min.to_s

id = instance_name + '-' + date_time

instance.create_snapshot({db_snapshot_identifier: id})

puts "Created snapshot #{id}"

5.7.8 Creating a Snapshot of a Cluster

The following example creates a snapshot for the Amazon RDS cluster represented by cluster_name in theus-west-2 region.

74 Chapter 5. AWS SDK for Ruby Code Examples

Page 79: AWS SDK for Ruby Developer Guide … · Working with Rubyin the Elastic Beanstalk Developer Guide. For deploying a Ruby on Rails application with AWS OpsWorks, seeDeploying Ruby on

AWS SDK for Ruby Developer Guide, Release 1.0

require 'aws-sdk'

rds = Aws::RDS::Resource.new(region: 'us-west-2')

cluster = rds.db_cluster(cluster_name)

date = Time.newdate_time = date.year.to_s + '-' + date.month.to_s + '-' + date.day.to_s→˓+ '-' + date.hour.to_s + '-' + date.min.to_s

id = cluster_name + '-' + date_time

cluster.create_snapshot({db_cluster_snapshot_identifier: id})

puts "Created cluster snapshot #{id}"

5.8 Amazon S3 Examples

You can use the following examples to access Amazon Simple Storage Service (Amazon S3) using theAWS SDK for Ruby. For more information about Amazon S3, see the Amazon S3 documentation.

Examples

5.8.1 Getting Information about All Buckets

The following example lists the names of up to 50 of your Amazon S3 buckets. Copy the code and save itas buckets.rb. Notice that although the Resource object is created in the us-west-2 region,Amazon S3 returns buckets to which you have access, regardless of the region they are in.

require 'aws-sdk'

region = 'us-west-2's3 = Aws::S3::Resource.new(region: region)

s3.buckets.limit(50).each do |b|puts "#{b.name}"

end

Note: When you specify a region, the buckets method calls the Client#list_buckets method,which returns a list of all buckets owned by the authenticated sender of the request. See GettingInformation about All Buckets in a Region to learn how to filter this list to get the buckets only in a specificregion.

5.8. Amazon S3 Examples 75

Page 80: AWS SDK for Ruby Developer Guide … · Working with Rubyin the Elastic Beanstalk Developer Guide. For deploying a Ruby on Rails application with AWS OpsWorks, seeDeploying Ruby on

AWS SDK for Ruby Developer Guide, Release 1.0

5.8.2 Getting Information about All Buckets in a Region

The following example lists the names of the first 50 buckets for the us-west-2 region. If you don’tspecify a limit, Amazon S3 lists all buckets in us-west-2.

require 'aws-sdk'

region = 'us-west-2's3 = Aws::S3::Resource.new(region: region)

s3.buckets.limit(50).each do |b|if s3.client.get_bucket_location(bucket: b.name).location_constraint ==

→˓regionputs "#{b.name}"

endend

Note: If a bucket is not in the region in which you instantiated your Resource object, the SDK emits awarning message when you call get_bucket_location. You can suppress this message byredirecting STDERR.

On Windows, append 2> nul to the command.

On Linux or iOS, append 2> /dev/null to the command.

5.8.3 Creating and Using an Amazon S3 Bucket

This example demonstrates how to use the AWS SDK for Ruby to:

1. Display a list of buckets in Amazon S3.

2. Create a bucket.

3. Upload an object (a file) to the bucket.

4. Copy files to the bucket.

5. Delete files from the bucket.

For the complete code for this example, see Complete Example.

Prerequisite Tasks

To set up and run this example, you must first:

1. Install the AWS SDK for Ruby. For more information, see Installing the AWS SDK for Ruby.

2. Set the AWS access credentials that the AWS SDK for Ruby will use to verify your access to AWSservices and resources. For more information, see Configuring the AWS SDK for Ruby.

76 Chapter 5. AWS SDK for Ruby Code Examples

Page 81: AWS SDK for Ruby Developer Guide … · Working with Rubyin the Elastic Beanstalk Developer Guide. For deploying a Ruby on Rails application with AWS OpsWorks, seeDeploying Ruby on

AWS SDK for Ruby Developer Guide, Release 1.0

Be sure the AWS credentials map to an AWS Identity and Access Management (IAM) entity with access tothe AWS actions and resources described in this example.

This example assumes you have set the credentials in the AWS credentials profile file and named the filedavid.

Configure the SDK

For this example, add require statements so that you can use the classes and methods provided by theAWS SDK for Ruby for Amazon S3 and work with JSON-formatted data. Then create an Aws::S3::Clientobject in the AWS Region where you want to create the bucket and the specified AWS profile. This codecreates the Aws::S3::Client object in the us-east-1 region. Additional variables are also declaredfor the two buckets used in this example.

require 'aws-sdk'require 'json'

profile_name = 'david'region = "us-east-1"bucket = 'doc-sample-bucket'my_bucket = 'david-cloud'

# S3

# Configure SDKs3 = Aws::S3::Client.new(profile: profile_name, region: region)

Get a List of Buckets

Call the list_buckets method. This returns an instance of the Aws::S3::Types::ListBucketsOutput class,which represents the list of buckets. Then use the buckets attribute of the ListBucketsOutput classto access the buckets’ properties, such as name for each bucket’s name.

resp = s3.list_bucketsresp.buckets.each do |bucket|puts bucket.name

end

Create a Bucket

Call the create_bucket method, specifying the bucket’s name.

Note: Bucket names must be unique across Amazon S3—not just unique to your AWS account.

s3.create_bucket(bucket: bucket)

5.8. Amazon S3 Examples 77

Page 82: AWS SDK for Ruby Developer Guide … · Working with Rubyin the Elastic Beanstalk Developer Guide. For deploying a Ruby on Rails application with AWS OpsWorks, seeDeploying Ruby on

AWS SDK for Ruby Developer Guide, Release 1.0

Upload an Object (a File) to a Bucket

Call the put_object method, specifying settings such as the bucket’s name and the name of the file to create.For the file’s contents, you can specify an instance of a Ruby File class or, in this example, a stringrepresenting the file’s data.

To confirm whether the file was uploaded successfully, call the list_objects_v2 method. This returns aninstance of the Aws::S3::Types::ListObjectsV2Output class, which represents the bucket’s objects. Thenuse the contents method of the ListObjectsV2Output class to access the objects’ properties, suchas key for each object’s name.

s3.put_object(bucket: bucket, key: "file1", body: "My first s3 object")

# Check the file existsresp = s3.list_objects_v2(bucket: bucket)resp.contents.each do |obj|

puts obj.keyend

Copy Files between Buckets

Call the copy_object method, specifying the name of the target bucket to receive the object (bucket), thenames of the source bucket and object to copy over (copy_source), and the name of the new object thatis copied over into the target bucket (key).

In this example, the name of the bucket containing the objects to copy over is #{my_bucket}, which isthe bucket named david-cloud. After the copy operation, test_file in the david-cloud bucketis renamed file2 in the doc-sample-bucket bucket, and test_file1 in the david-cloudbucket is renamed file3 in the doc-sample-bucket bucket.

s3.copy_object(bucket: bucket,copy_source: "#{my_bucket}/test_file",key: 'file2')

s3.copy_object(bucket: bucket,copy_source: "#{my_bucket}/test_file1",key: 'file3')

Delete Files from a Bucket

Call the delete_objects method. For the delete argument, use an instance of the Aws::S3::Types::Deletetype to represent the objects to delete. In this example, objects represents two files to delete.

To confirm whether the files were deleted successfully, call the list_objects_v2 method as before.This time, when you use the contents method of the class, the deleted file names (represented here bykey) should not be displayed.

s3.delete_objects(bucket: 'doc-sample-bucket',delete: {

78 Chapter 5. AWS SDK for Ruby Code Examples

Page 83: AWS SDK for Ruby Developer Guide … · Working with Rubyin the Elastic Beanstalk Developer Guide. For deploying a Ruby on Rails application with AWS OpsWorks, seeDeploying Ruby on

AWS SDK for Ruby Developer Guide, Release 1.0

objects: [{

key: 'file2'},{

key: 'file3'}

]}

)

# Verify objects now have been deletedresp = s3.list_objects_v2(bucket: bucket)resp.contents.each do |obj|

puts obj.keyend

Complete Example

Here is the complete code for this example.

require 'aws-sdk'require 'json'

profile_name = 'david'region = "us-east-1"bucket = 'doc-sample-bucket'my_bucket = 'david-cloud'

# S3

# Configure SDKs3 = Aws::S3::Client.new(profile: profile_name, region: region)

# Display a List of Amazon S3 Bucketsresp = s3.list_bucketsresp.buckets.each do |bucket|puts bucket.name

end

# Create a S3 bucket from S3::clients3.create_bucket(bucket: bucket)

# Upload a file to s3 bucket, directly putting string datas3.put_object(bucket: bucket, key: "file1", body: "My first s3 object")

# Check the file existsresp = s3.list_objects_v2(bucket: bucket)resp.contents.each do |obj|puts obj.key

end

5.8. Amazon S3 Examples 79

Page 84: AWS SDK for Ruby Developer Guide … · Working with Rubyin the Elastic Beanstalk Developer Guide. For deploying a Ruby on Rails application with AWS OpsWorks, seeDeploying Ruby on

AWS SDK for Ruby Developer Guide, Release 1.0

# Copy files from bucket to buckets3.copy_object(bucket: bucket,

copy_source: "#{my_bucket}/test_file",key: 'file2')

s3.copy_object(bucket: bucket,copy_source: "#{my_bucket}/test_file1",key: 'file3')

# Delete multiple objects in a single HTTP requests3.delete_objects(

bucket: 'doc-sample-bucket',delete: {

objects: [{

key: 'file2'},{

key: 'file3'}

]}

)

# Verify objects now have been deletedresp = s3.list_objects_v2(bucket: bucket)resp.contents.each do |obj|puts obj.key

end

Alternative Approaches

The following example creates a bucket named my-bucket in the us-west-2 region. This exampleuses an instance of the Aws::S3::Resource class instead of the Aws::S3::Client class.

require 'aws-sdk'

s3 = Aws::S3::Resource.new(region: 'us-west-2')s3.create_bucket(bucket: 'my-bucket')

5.8.4 Determining Whether a Bucket Exists

There are two cases in which you would want to determine whether a bucket already exists. You performthese tests in lieu of receiving an exception if the condition fails:

• You want to determine whether a bucket with a specific name already exists among all buckets, evenones to which you do not have access. This test helps prevent you from trying to create a bucket withthe name of an existing bucket, which causes an exception.

80 Chapter 5. AWS SDK for Ruby Code Examples

Page 85: AWS SDK for Ruby Developer Guide … · Working with Rubyin the Elastic Beanstalk Developer Guide. For deploying a Ruby on Rails application with AWS OpsWorks, seeDeploying Ruby on

AWS SDK for Ruby Developer Guide, Release 1.0

• You want to perform an operation, such as add an item to a bucket, only on a bucket to which youhave access.

The following example sets bucket_exists to true if a bucket with the name my-bucket alreadyexists. The region: parameter to Resource has no effect on the result.

require 'aws-sdk'

s3 = Aws::S3::Resource.new(region: 'us-west-2')bucket_exists = s3.bucket('my-bucket').exists?

The following example sets bucket_exists to true if the bucket with the name my-bucket existsand you have access to the bucket. Again, the region parameter to Client has no effect on the result.

require 'aws-sdk'

bucket_exists = falseclient = Aws::S3::Client.new(region: 'us-west-2')

beginresp = client.head_bucket({bucket: bucket_name, use_accelerate_endpoint:

→˓false})bucket_exists = true

rescueend

5.8.5 Getting Information about Bucket Items

A presigned URL gives you access to the object identified in the URL, if the creator of the presigned URLhas permissions to access that object. You can use a presigned URL to allow a user to click a link and seean item without having to make the item public.

The following example lists the names and presigned URLs of the first 50 items of the bucket my-bucketin the us-west-2 region. If a limit is not specified, Amazon S3 lists up to 1000 items.

require 'aws-sdk'

s3 = Aws::S3::Resource.new(region: 'us-west-2')

bucket = s3.bucket('my-bucket')

# Show only the first 50 itemsbucket.objects.limit(50).each do |item|

puts "Name: #{item.key}"puts "URL: #{item.presigned_url(:get)}"

end

5.8. Amazon S3 Examples 81

Page 86: AWS SDK for Ruby Developer Guide … · Working with Rubyin the Elastic Beanstalk Developer Guide. For deploying a Ruby on Rails application with AWS OpsWorks, seeDeploying Ruby on

AWS SDK for Ruby Developer Guide, Release 1.0

5.8.6 Uploading an Item to a Bucket

The following example uploads the item (file) C:file.txt to the bucket my-bucket in theus-west-2 region. Because C:file.txt is the fully qualified name of the file, the name of the item isset to the name of the file.

require 'aws-sdk'

s3 = Aws::S3::Resource.new(region: 'us-west-2')

file = 'C:\file.txt'bucket = 'my-bucket'

# Get just the file namename = File.basename(file)

# Create the object to uploadobj = s3.bucket(bucket).object(name)

# Upload itobj.upload_file(file)

5.8.7 Uploading an Item with Metadata to a Bucket

The following example uploads the item (file) C:file.txt with the metadata key-value pair answerand 42 to the bucket my-bucket in the us-west-2 region. Because C:file.txt is the fullyqualified name of the file, the name of the item is set to the file name.

require 'aws-sdk'

s3 = Aws::S3::Resource.new(region: 'us-west-2')

file = 'C:\file.txt'bucket = 'my-bucket'

# Get just the file namename = File.basename(file)

# Create the object to uploadobj = s3.bucket(bucket).object(name)

# Metadata to addmetadata = {"answer" => "42"}

# Upload itobj.upload_file(file, metadata: metadata)

82 Chapter 5. AWS SDK for Ruby Code Examples

Page 87: AWS SDK for Ruby Developer Guide … · Working with Rubyin the Elastic Beanstalk Developer Guide. For deploying a Ruby on Rails application with AWS OpsWorks, seeDeploying Ruby on

AWS SDK for Ruby Developer Guide, Release 1.0

5.8.8 Downloading an Object from a Bucket into a File

The following example gets the contents of the item my-item from the bucket my-bucket in theus-west-2 region, and saves it to the my-item.txt file in the ./my-code directory.

require 'aws-sdk'

s3 = Aws::S3::Resource.new(region: 'us-west-2')

# Create the object to retrieveobj = s3.bucket('my-bucket').object('my-item')

# Get the item's content and save it to a fileobj.get(response_target: './my-code/my-item.txt')

5.8.9 Changing the Properties for a Bucket Item

The following example adds public read-only access, sets server-side encryption to AES-256, and sets thestorage class to Reduced Redundancy for the item my-item in the bucket my-bucket in theus-west-2 region.

require 'aws-sdk'

args_list = {}args_list[:bucket] = 'my-bucket'args_list[:key] = 'my-item'

# Where we are getting the source to copy fromargs_list[:copy_source] = 'my-bucket/my-item'

# The acl can be any of:# private, public-read, public-read-write, authenticated-read, aws-exec-read,→˓bucket-owner-read, bucket-owner-full-controlargs_list[:acl] = 'public-read'

# The encryption can be any of:# AES256, aws:kmsargs_list[:server_side_encryption] = 'AES256'

# The storage_class can be any of:# STANDARD, REDUCED_REDUNDANCY, STANDARD_IAargs_list[:storage_class] = 'REDUCED_REDUNDANCY'

client = Aws::S3::Client.new(region: 'us-west-2')

client.copy_object(args_list)

5.8.10 Triggering a Notification When an Item is Added to a Bucket

You can trigger a notification when there is a change in the objects in a bucket. These changes include:

5.8. Amazon S3 Examples 83

Page 88: AWS SDK for Ruby Developer Guide … · Working with Rubyin the Elastic Beanstalk Developer Guide. For deploying a Ruby on Rails application with AWS OpsWorks, seeDeploying Ruby on

AWS SDK for Ruby Developer Guide, Release 1.0

• When an object is added to the bucket

• When an object is removed from the bucket

• When an object stored with Reduced Redundancy is lost

You can configure the service to send a notification to:

• An Amazon SNS topic

• An Amazon SQS queue

• A Lambda function

To create a bucket notification

1. Grant Amazon S3 permission to publish an item to a queue or topic, or invoke a Lambda function.

2. Set the bucket’s Notification Configuration to point to the queue, topic, or function.

After you do these steps, your application can respond to the information. For example, the Lambda topicProgramming Model describes how to use the various programming languages that Lambda supports.

Enabling Amazon S3 to Send a Notification

Learn how to configure an Amazon Simple Notification Service topic or Amazon Simple Queue Servicequeue, or create a Lambda function so that Amazon S3 can send a notification to them.

• Enabling a Resource to Publish to a Topic

• Enabling a Resource to Publish to a Queue in Amazon SQS

• Configuring a Lambda Function to Receive Notifications

Creating an Amazon S3 Bucket Notification

The following example enables the Amazon S3 bucket my-bucket to send a notification to the followingwhen an item is added to the bucket:

• The Amazon SNS topic with the ARN my-topic-arn

• The Amazon SQS queue with the ARN my-queue-arn

• The Lambda function with the ARN my-function-arn

require 'aws-sdk'

req = {}req[:bucket] = bucket_name

events = ['s3:ObjectCreated:*']

notification_configuration = {}

# Add functionlc = {}

84 Chapter 5. AWS SDK for Ruby Code Examples

Page 89: AWS SDK for Ruby Developer Guide … · Working with Rubyin the Elastic Beanstalk Developer Guide. For deploying a Ruby on Rails application with AWS OpsWorks, seeDeploying Ruby on

AWS SDK for Ruby Developer Guide, Release 1.0

lc[:lambda_function_arn] = 'my-function-arn'lc[:events] = eventslambda_configurations = []lambda_configurations << lc

notification_configuration[:lambda_function_configurations] = lambda_→˓configurations

# Add queueqc = {}

qc[:queue_arn] = 'my-topic-arn'qc[:events] = eventsqueue_configurations = []queue_configurations << qc

notification_configuration[:queue_configurations] = queue_configurations

# Add topictc = {}

tc[:topic_arn] = 'my-topic-arn'tc[:events] = eventstopic_configurations = []topic_configurations << tc

notification_configuration[:topic_configurations] = topic_configurations

req[:notification_configuration] = notification_configuration

req[:use_accelerate_endpoint] = false

s3 = Aws::S3::Client.new(region: 'us-west-2')

s3.put_bucket_notification_configuration(req)

5.8.11 Creating a Bucket LifeCycle Rule Configuration Template

If you have (or plan to create) a non-trivial number of objects and want to specify when to move them tolong-term storage or delete them, you can save a lot of time by creating a template for the lifecycle rulesand applying that template to all of your buckets.

The process includes these steps:

1. Manually modify the lifecycle settings on an existing bucket.

2. Save the rules.

3. Apply the rules to your other buckets.

Start with the following rule:

5.8. Amazon S3 Examples 85

Page 90: AWS SDK for Ruby Developer Guide … · Working with Rubyin the Elastic Beanstalk Developer Guide. For deploying a Ruby on Rails application with AWS OpsWorks, seeDeploying Ruby on

AWS SDK for Ruby Developer Guide, Release 1.0

Run the following code to produce a JSON representation of that rule. Save the output asdefault.json.

require 'aws-sdk'

s3 = Aws::S3::Client.new(region: 'us-west-2')resp = s3.get_bucket_lifecycle_configuration(bucket: 'default')

resp.rules.each do |rule|rule.to_hash.to_json

end

The output should look like the following:

[{"expiration":{"date":null,"days":425},"id":"default","prefix":"","status":→˓"Enabled","transitions":[{"date":null,"days":30,"storage_class":"STANDARD_IA→˓"},{"date":null,"days":60,"storage_class":"GLACIER"}],"noncurrent_version_→˓transitions":[],"noncurrent_version_expiration":null}]

Now that you have the JSON for a lifecycle rule, you can apply it to any other bucket using the followingexample, which takes the rule from default.json and applies it to the bucket other_bucket:

require 'aws-sdk'require 'json'

class Aws::S3::Types::LifecycleExpirationdef to_map

map = Hash.newself.members.each { |m| map[m] = self[m] }map

end

def to_json(*a)to_map.to_json(*a)

end

86 Chapter 5. AWS SDK for Ruby Code Examples

Page 91: AWS SDK for Ruby Developer Guide … · Working with Rubyin the Elastic Beanstalk Developer Guide. For deploying a Ruby on Rails application with AWS OpsWorks, seeDeploying Ruby on

AWS SDK for Ruby Developer Guide, Release 1.0

end

class Aws::S3::Types::Transitiondef to_map

map = Hash.newself.members.each { |m| map[m] = self[m] }map

end

def to_json(*a)to_map.to_json(*a)

endend

class Aws::S3::Types::LifecycleRuledef to_map

map = Hash.newself.members.each { |m| map[m] = self[m] }map

end

def to_json(*a)to_map.to_json(*a)

endend

# Pull in contents as a stringvalue = File.open('default.json', "rb").readjson_data = JSON.parse(value, opts={symbolize_names: true})

s3 = Aws::S3::Client.new(region: 'us-west-2')s3.put_bucket_lifecycle_configuration(:bucket => 'other_bucket', :lifecycle_→˓configuration => {:rules => json_data})

Best Practice

We recommend that you enable the AbortIncompleteMultipartUpload lifecycle rule on your Amazon S3buckets.

This rule directs Amazon S3 to abort multipart uploads that don’t complete within a specified number ofdays after being initiated. When the set time limit is exceeded, Amazon S3 aborts the upload and thendeletes the incomplete upload data.

For more information, see Lifecycle Configuration for a Bucket with Versioning in the Amazon S3 UserGuide.

5.8.12 Creating a Bucket Policy with Ruby

This example demonstrates how to use the AWS SDK for Ruby to:

5.8. Amazon S3 Examples 87

Page 92: AWS SDK for Ruby Developer Guide … · Working with Rubyin the Elastic Beanstalk Developer Guide. For deploying a Ruby on Rails application with AWS OpsWorks, seeDeploying Ruby on

AWS SDK for Ruby Developer Guide, Release 1.0

1. Create a bucket in Amazon Simple Storage Service (Amazon S3).

2. Define a bucket policy.

3. Add the policy to the bucket.

4. Change the policy.

5. Remove the policy from the bucket.

6. Delete the bucket.

For the complete code for this example, see Complete Example.

Prerequisite Tasks

To set up and run this example, you must first:

1. Install the AWS SDK for Ruby. For more information, see Installing the AWS SDK for Ruby.

2. Set the AWS access credentials that the AWS SDK for Ruby will use to verify your access to AWSservices and resources. For more information, see Configuring the AWS SDK for Ruby.

Be sure the AWS credentials map to an AWS Identity and Access Management (IAM) entity with access tothe AWS actions and resources described in this example.

This example assumes you have set the credentials in the AWS credentials profile file or in theAWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY environment variables on your local system.

Configure the SDK

To configure the SDK for this example, add a require statement so you can use the classes and methodsprovided by the AWS SDK for Ruby for Amazon S3. Then create an Aws::S3::Client object in the AWSRegion where you want to create the bucket. This code creates the Aws::S3::Client object in theus-west-2 region.

require 'aws-sdk'

s3 = Aws::S3::Client.new(region: "us-west-2")

Create a Bucket

Call the create_bucket method, specifying the bucket’s name. This code uses a variable named bucket torepresent the bucket’s name. Substitute example-bucket-name for your bucket’s name.

Note: Bucket names must be unique across Amazon S3—not just unique to your AWS account.

If you already have a bucket you want to use, you don’t have to call create_bucket.

88 Chapter 5. AWS SDK for Ruby Code Examples

Page 93: AWS SDK for Ruby Developer Guide … · Working with Rubyin the Elastic Beanstalk Developer Guide. For deploying a Ruby on Rails application with AWS OpsWorks, seeDeploying Ruby on

AWS SDK for Ruby Developer Guide, Release 1.0

bucket = "example-bucket-name"

s3.create_bucket(bucket: bucket)

Define a Bucket Policy

Declare a Ruby hash that represents the policy. Then call the to_json method on the hash to convert it toa JSON object. This code uses a variable named policy that contains the policy definition. This policyallows the specified user to have full control over the example-bucket-name (represented by#{bucket}). Substitute arn:aws:iam::111122223333:user/Alice with the AmazonResource Name (ARN) of the AWS Identity and Access Management (IAM) user you want to use.

policy = {"Version" => "2012-10-17","Statement" => [

{"Effect" => "Allow","Principal" => {

"AWS" => ["arn:aws:iam::111122223333:user/Alice"

]},"Action" => "s3:*","Resource" => [

"arn:aws:s3:::#{bucket}"]

}]

}.to_json

For examples of the types of policies you can define, see Bucket Policy Examples in the Amazon S3Developer Guide.

Add the Policy to the Bucket

Call the put_bucket_policy method, specifying the name of the bucket and the policy definition.

s3.put_bucket_policy(bucket: bucket,policy: policy

)

Change the Policy

You can call the put_bucket_policy method again with a complete replacement policy. However,you can also make incremental updates to an existing policy, which can reduce the amount of code youneed to write. To do this, retrieve the current policy by calling the get_bucket_policy method. Next, parse

5.8. Amazon S3 Examples 89

Page 94: AWS SDK for Ruby Developer Guide … · Working with Rubyin the Elastic Beanstalk Developer Guide. For deploying a Ruby on Rails application with AWS OpsWorks, seeDeploying Ruby on

AWS SDK for Ruby Developer Guide, Release 1.0

the JSON object that is returned into a Ruby hash. Then make your incremental changes to the policy. Forexample, this code changes the ARN of the IAM entity. After you make your changes, call theput_bucket_policy method again. Be sure to call the to_json method on the hash to convert itback to a JSON object before applying the changed policy to the bucket.

policy_string = s3.get_bucket_policy(bucket: bucket).policy.readpolicy_json = JSON.parse(policy_string)

policy_json["Statement"][0]["Principal"]["AWS"] = "arn:aws:iam::111122223333:→˓root"

s3.put_bucket_policy(bucket: bucket,policy: policy_json.to_json

)

Clean Up

To remove the policy from the bucket, call the delete_bucket_policy method, specifying the name of thebucket.

To delete the bucket, call the delete_bucket method, specifying the name of the bucket.

s3.delete_bucket_policy(bucket: bucket)s3.delete_bucket(bucket: bucket)

Complete Example

Here is the complete code for this example.

require 'aws-sdk'

s3 = Aws::S3::Client.new(region: "us-west-2")

bucket = "example-bucket-name"

s3.create_bucket(bucket: bucket)

policy = {"Version" => "2012-10-17","Statement" => [

{"Effect" => "Allow","Principal" => {

"AWS" => ["arn:aws:iam::111122223333:user/Alice"

]},"Action" => "s3:*","Resource" => [

90 Chapter 5. AWS SDK for Ruby Code Examples

Page 95: AWS SDK for Ruby Developer Guide … · Working with Rubyin the Elastic Beanstalk Developer Guide. For deploying a Ruby on Rails application with AWS OpsWorks, seeDeploying Ruby on

AWS SDK for Ruby Developer Guide, Release 1.0

"arn:aws:s3:::#{bucket}"]

}]

}.to_json

s3.put_bucket_policy(bucket: bucket,policy: policy

)

policy_string = s3.get_bucket_policy(bucket: bucket).policy.readpolicy_json = JSON.parse(policy_string)

policy_json["Statement"][0]["Principal"]["AWS"] = "arn:aws:iam::111122223333:→˓root"

s3.put_bucket_policy(bucket: bucket,policy: policy_json.to_json

)

s3.delete_bucket_policy(bucket: bucket)s3.delete_bucket(bucket: bucket)

5.8.13 Configuring a Bucket for Cross-Origin Resource Sharing (CORS)

This example demonstrates how to use the AWS SDK for Ruby to:

1. Configure CORS settings for an Amazon S3 bucket.

2. Get the CORS settings for a bucket.

For more information about CORS support in Amazon S3, see Cross-Origin Resource Sharing (CORS) inthe Amazon S3 Developer Guide.

For the complete code for this example, see Complete Example.

Prerequisite Tasks

To set up and run this example, you must first:

1. Install the AWS SDK for Ruby. For more information, see Installing the AWS SDK for Ruby.

2. Set the AWS access credentials that the AWS SDK for Ruby will use to verify your access to AWSservices and resources. For more information, see Configuring the AWS SDK for Ruby.

3. Create an Amazon S3 bucket or identify an existing bucket in your AWS account.

Be sure the AWS credentials map to an AWS Identity and Access Management (IAM) entity with access tothe AWS actions and resources described in this example.

This example assumes:

5.8. Amazon S3 Examples 91

Page 96: AWS SDK for Ruby Developer Guide … · Working with Rubyin the Elastic Beanstalk Developer Guide. For deploying a Ruby on Rails application with AWS OpsWorks, seeDeploying Ruby on

AWS SDK for Ruby Developer Guide, Release 1.0

• You have set the credentials in the AWS credentials profile file and the profile is named david.

• Your bucket is named doc-sample-bucket.

Configure the SDK

For this example, add a require statement so that you can use the classes and methods provided by theAWS SDK for Ruby for Amazon S3. Then create an Aws::S3::Client object in the AWS Region where youwant to create the bucket and the specified AWS profile. This code creates the Aws::S3::Client objectin the us-east-1 region. An additional variable is also declared for the bucket used in this example.

require 'aws-sdk'

profile_name = 'david'region = 'us-east-1'bucket = 'doc-sample-bucket'

# S3 - Configuring an S3 Bucket

# Create a S3 clients3 = Aws::S3::Client.new(profile: profile_name, region:region)

Configure CORS for a Bucket

Call the put_bucket_cors method, providing the name of the bucket and the CORS configuration settings.

s3.put_bucket_cors(bucket: bucket,cors_configuration: cors_configuration

)

For the CORS configuration settings, declare an Aws::S3::Types::CORSConfiguration hash. Specify thingssuch as the HTTP methods that the specified origins are allowed to execute (allowed_methods), theorigins you want customers to be able to access the bucket from (allowed_origins), and the headersin the response you want customers to be able to access from their applications (for example, from aJavaScript XMLHttpRequest object, shown here in expose_headers).

cors_configuration = {cors_rules: [

{allowed_methods: allowed_methods,allowed_origins: ["*"],expose_headers: ["ExposeHeader"],

},]

}

For the HTTP methods that the specified origins are allowed to execute, you could specify them inline or,as shown here, you could get them from the user at the command line.

92 Chapter 5. AWS SDK for Ruby Code Examples

Page 97: AWS SDK for Ruby Developer Guide … · Working with Rubyin the Elastic Beanstalk Developer Guide. For deploying a Ruby on Rails application with AWS OpsWorks, seeDeploying Ruby on

AWS SDK for Ruby Developer Guide, Release 1.0

allowed_methods = []ARGV.each do |arg|

case arg.upcasewhen "POST"

allowed_methods << "POST"when "GET"

allowed_methods << "GET"when "PUT"

allowed_methods << "PUT"when "PATCH"

allowed_methods << "PATCH"when "DELETE"

allowed_methods << "DELETE"when "HEAD"

allowed_methods << "HEAD"else

puts "#{arg} is not a valid HTTP method"end

end

For example, assuming the code file is named doc_sample_code_s3_bucket_cors.rb, and youwant to allow the specified origins to execute only GET and POST methods, here is how the user could runthe code from the command line.

ruby doc_sample_code_s3_bucket_cors.rb get post

Get the CORS Settings for a Bucket

Call the get_bucket_cors method, providing the name of the bucket. The get_bucket_cors methodreturns an Aws::S3::Types::GetBucketCorsOutput object. This object’s cors_rules attribute returns anarray of Aws::S3::Types::CORSRule objects, which represent the bucket’s CORS settings.

resp = s3.get_bucket_cors(bucket: bucket)puts resp.cors_rules

Complete Example

Here is the complete code for this example.

require 'aws-sdk'

profile_name = 'david'region = 'us-east-1'bucket = 'doc-sample-bucket'

# S3 - Configuring an S3 Bucket

# Create a S3 clients3 = Aws::S3::Client.new(profile: profile_name, region:region)

5.8. Amazon S3 Examples 93

Page 98: AWS SDK for Ruby Developer Guide … · Working with Rubyin the Elastic Beanstalk Developer Guide. For deploying a Ruby on Rails application with AWS OpsWorks, seeDeploying Ruby on

AWS SDK for Ruby Developer Guide, Release 1.0

# Setting a Bucket CORS Configuration

# Create array of allowed methods parameter based on command line parametersallowed_methods = []ARGV.each do |arg|

case arg.upcasewhen "POST"

allowed_methods << "POST"when "GET"

allowed_methods << "GET"when "PUT"

allowed_methods << "PUT"when "PATCH"

allowed_methods << "PATCH"when "DELETE"

allowed_methods << "DELETE"when "HEAD"

allowed_methods << "HEAD"else

puts "#{arg} is not a valid HTTP method"end

end

# Create CORS configuration hashcors_configuration = {

cors_rules: [{

allowed_methods: allowed_methods,allowed_origins: ["*"],expose_headers: ["ExposeHeader"],

},]

}

# Set the new CORS configuration on the selected buckets3.put_bucket_cors(

bucket: bucket,cors_configuration: cors_configuration

)

# Retrieving a Bucket CORS Configurationresp = s3.get_bucket_cors(bucket: bucket)puts resp.cors_rules

# To run the example, type the following at the command line including one or→˓more HTTP methods as shown# ruby doc_sample_code_s3_bucket_cors.rb get post

94 Chapter 5. AWS SDK for Ruby Code Examples

Page 99: AWS SDK for Ruby Developer Guide … · Working with Rubyin the Elastic Beanstalk Developer Guide. For deploying a Ruby on Rails application with AWS OpsWorks, seeDeploying Ruby on

AWS SDK for Ruby Developer Guide, Release 1.0

5.8.14 Managing Amazon S3 Bucket and Object Access Permissions

This example demonstrates how to use the AWS SDK for Ruby to:

1. Set a predefined grant (also known as a canned ACL) for a bucket in Amazon S3.

2. Add an object to the bucket.

3. Set a canned ACL for an object in the bucket.

4. Get the bucket’s current ACL.

For the complete code for this example, see Complete Example.

Prerequisite Tasks

To set up and run this example, you must first:

1. Install the AWS SDK for Ruby. For more information, see Installing the AWS SDK for Ruby.

2. Set the AWS access credentials that the AWS SDK for Ruby will use to verify your access to AWSservices and resources. For more information, see Configuring the AWS SDK for Ruby.

Be sure the AWS credentials map to an AWS Identity and Access Management (IAM) entity with access tothe AWS actions and resources described in this example.

This example assumes you have set the credentials in the AWS credentials profile file or in theAWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY environment variables on your local system.

Configure the SDK

For this example, add a require statement so that you can use the classes and methods provided by theAWS SDK for Ruby for Amazon S3. Then create an Aws::S3::Client object in the AWS Region where youwant to create the bucket. This code creates the Aws::S3::Client object in the us-west-2 region.This code also declares a variable representing the bucket.

require 'aws-sdk'

# Create a S3 clientclient = Aws::S3::Client.new(region: 'us-west-2')

Set a Canned ACL for a Bucket

Call the put_bucket_acl method, specifying the names of the canned ACL and the bucket. This code setsthe public-read canned ACL on the bucket, which enables full control for the bucket’s owner andread-only access for everyone else.

client.put_bucket_acl({acl: "public-read",bucket: bucket,

})

5.8. Amazon S3 Examples 95

Page 100: AWS SDK for Ruby Developer Guide … · Working with Rubyin the Elastic Beanstalk Developer Guide. For deploying a Ruby on Rails application with AWS OpsWorks, seeDeploying Ruby on

AWS SDK for Ruby Developer Guide, Release 1.0

For more information about canned ACLs, see Canned ACL in Access Control List (ACL) Overview inthe Amazon S3 Developer Guide.

To confirm this setting, call the Ruby Net::HTTP.get method to attempt to get the bucket’s content.

bucket_path = "http://#{bucket}.s3-us-west-2.amazonaws.com/"resp = Net::HTTP.get(URI(bucket_path))puts "Content of unsigned request to #{bucket_path}:\n\n#{resp}\n\n"

Upload an Object to a Bucket

Call the put_object method, specifying the names of the bucket and object and the object’s content. Thiscode declares a variable representing the object.

object_key = "my-key"# Put an object in the public bucketclient.put_object({

bucket: bucket,key: object_key,body: 'Hello World',

})

Set a Canned ACL for an Object

By default, you can’t get the contents of the object in the bucket. To confirm this behavior, call the RubyNet::HTTP.get method to attempt to get the object’s content.

object_path = "http://#{bucket}.s3-us-west-2.amazonaws.com/#{object_key}"resp = Net::HTTP.get(URI(object_path))puts "Content of unsigned request to #{object_path}:\n\n#{resp}\n\n"

To change this behavior, call the put_object_acl method, specifying the names of the canned ACL, bucket,and object. This code sets the public-read canned ACL on the object, which enables full control for theobject’s owner and read-only access for everyone else. After the call, try to get the object’s content again.

client.put_object_acl({acl: "public-read",bucket: bucket,key: object_key,

})object_path = "http://#{bucket}.s3-us-west-2.amazonaws.com/#{object_key}"puts "Now I can access object (#{object_key}) :\n#{Net::HTTP.get(URI(object_→˓path))}\n\n"

Get a Bucket’s Current ACL

Call the get_bucket_acl method, specifying the name of the bucket. The get_bucket_acl methodreturns an instance of the Aws::S3::Types::GetBucketAclOutput class. Use the grants attribute of the

96 Chapter 5. AWS SDK for Ruby Code Examples

Page 101: AWS SDK for Ruby Developer Guide … · Working with Rubyin the Elastic Beanstalk Developer Guide. For deploying a Ruby on Rails application with AWS OpsWorks, seeDeploying Ruby on

AWS SDK for Ruby Developer Guide, Release 1.0

GetBucketAclOutput class to list the bucket’s current ACL.

resp = client.get_bucket_acl(bucket: bucket)puts resp.grants

Complete Example

Here is the complete code for this example.

require 'aws-sdk'

# Create a S3 clientclient = Aws::S3::Client.new(region: 'us-west-2')

bucket = 'my-bucket'# Sets a bucket to public-readclient.put_bucket_acl({

acl: "public-read",bucket: bucket,

})

object_key = "my-key"# Put an object in the public bucketclient.put_object({

bucket: bucket,key: object_key,body: 'Hello World',

})

# Accessing an object in the bucket with unauthorize requestbucket_path = "http://#{bucket}.s3-us-west-2.amazonaws.com/"resp = Net::HTTP.get(URI(bucket_path))puts "Content of unsigned request to #{bucket_path}:\n\n#{resp}\n\n"

# However, accessing the object is denied since object Acl is not public-readobject_path = "http://#{bucket}.s3-us-west-2.amazonaws.com/#{object_key}"resp = Net::HTTP.get(URI(object_path))puts "Content of unsigned request to #{object_path}:\n\n#{resp}\n\n"

# Setting the object to public-readclient.put_object_acl({

acl: "public-read",bucket: bucket,key: object_key,

})object_path = "http://#{bucket}.s3-us-west-2.amazonaws.com/#{object_key}"puts "Now I can access object (#{object_key}) :\n#{Net::HTTP.get(URI(object_→˓path))}\n\n"

# Setting bucket to private againclient.put_bucket_acl({

bucket: bucket,

5.8. Amazon S3 Examples 97

Page 102: AWS SDK for Ruby Developer Guide … · Working with Rubyin the Elastic Beanstalk Developer Guide. For deploying a Ruby on Rails application with AWS OpsWorks, seeDeploying Ruby on

AWS SDK for Ruby Developer Guide, Release 1.0

acl: 'private',})

# Get current bucket Aclresp = client.get_bucket_acl(bucket: bucket)puts resp.grants

resp = Net::HTTP.get(URI(bucket_path))puts "Content of unsigned request to #{bucket_path}:\n\n#{resp}\n\n"

5.8.15 Using a Amazon S3 Bucket to Host a Website

This example demonstrates how to use the AWS SDK for Ruby to:

1. Create an Amazon S3 bucket.

2. Get the bucket website’s configuration.

3. Add objects to the bucket.

4. Set the bucket website’s configuration.

5. Access the bucket website’s documents.

6. Delete the bucket website.

7. Delete the bucket.

For information about bucket website hosting, see Configure a Bucket for Website Hosting in the AmazonS3 Developer Guide.

For the complete code for this example, see Complete Example.

Prerequisite Tasks

To set up and run this example, you must first:

1. Install the AWS SDK for Ruby. For more information, see Installing the AWS SDK for Ruby.

2. Set the AWS access credentials that the AWS SDK for Ruby will use to verify your access to AWSservices and resources. For more information, see Configuring the AWS SDK for Ruby.

Be sure the AWS credentials map to an AWS Identity and Access Management (IAM) entity with access tothe AWS actions and resources described in this example.

This example assumes you have set the credentials in the AWS credentials profile file or in theAWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY environment variables on your local system.

Configure the SDK

For this example, add a require statement so that you can use the classes and methods provided by theAWS SDK for Ruby for Amazon S3. Then create an Aws::S3::Client object in the AWS Region where you

98 Chapter 5. AWS SDK for Ruby Code Examples

Page 103: AWS SDK for Ruby Developer Guide … · Working with Rubyin the Elastic Beanstalk Developer Guide. For deploying a Ruby on Rails application with AWS OpsWorks, seeDeploying Ruby on

AWS SDK for Ruby Developer Guide, Release 1.0

want to create the bucket and the specified AWS profile. This code creates the Aws::S3::Clientobject in the us-east-2 region.

An additional variable is also declared for the bucket used in this example. To help ensure the bucket nameis unique across all AWS accounts, an additional require statement is added, and the SecureRandommodule’s uuid method is called to generate a unique identifier. This identifier is inserted into the name ofthe bucket to be created later in this sample.

require 'aws-sdk'

# Using Random UUIDs to Avoid Collisions when Testingrequire 'securerandom'bucket = "example-test-bucket-#{SecureRandom.uuid}"

# Setups3 = Aws::S3::Client.new(region: "us-west-2")

Create a Bucket

Call the create_bucket method, supplying the name of the bucket to create.

s3.create_bucket(bucket: bucket)

Get a Bucket Website’s Configuration

Call the get_bucket_website method, supplying the name of the bucket. By default, a bucket is notconfigured as a website. To confirm this behavior, call the get_bucket_website method. This returnsan error, because there is no website configuration for the bucket.

begins3.get_bucket_website(bucket: bucket)

rescue Aws::S3::Errors::NoSuchWebsiteConfigurationputs "No bucket website configuration present."

end

Add an Object to a Bucket

Call the put_object method, supplying the name of the bucket and object, the object’s contents, and theobject’s access permissions set. This example adds two webpages to the bucket.

s3.put_object(bucket: bucket,key: "index.html",body: "Hello, Amazon S3!",acl: "public-read"

)s3.put_object(

bucket: bucket,

5.8. Amazon S3 Examples 99

Page 104: AWS SDK for Ruby Developer Guide … · Working with Rubyin the Elastic Beanstalk Developer Guide. For deploying a Ruby on Rails application with AWS OpsWorks, seeDeploying Ruby on

AWS SDK for Ruby Developer Guide, Release 1.0

key: "error.html",body: "Page not found!",acl: "public-read"

)

Set a Bucket Website’s Configuration

Call the put_bucket_website method, supplying the name of the bucket and the website configuration. Forthe website configuration, use an Aws::S3::Types::WebsiteConfiguration hash, supplying the website’sindex and error webpages.

s3.put_bucket_website(bucket: bucket,website_configuration: {

index_document: {suffix: "index.html"

},error_document: {

key: "error.html"}

})

Access a Bucket Website’s Documents

Call the Ruby Net::HTTP.get method, supplying the address to the document in the bucket website.

index_path = "http://#{bucket}.s3-website-us-west-2.amazonaws.com/"error_path = "http://#{bucket}.s3-website-us-west-2.amazonaws.com/nonexistant.→˓html"

puts "Index Page Contents:\n#{Net::HTTP.get(URI(index_path))}\n\n"puts "Error Page Contents:\n#{Net::HTTP.get(URI(error_path))}\n\n"

Delete a Bucket Website

Call the delete_bucket_website method, supplying the name of the bucket.

s3.delete_bucket_website(bucket: bucket)

Delete a Bucket

Call the bucket method of an Aws::S3::Resource object, supplying the name of the bucket. This returns anAws::S3::Bucket object. Then call the Aws::S3::Bucket object’s delete method.

100 Chapter 5. AWS SDK for Ruby Code Examples

Page 105: AWS SDK for Ruby Developer Guide … · Working with Rubyin the Elastic Beanstalk Developer Guide. For deploying a Ruby on Rails application with AWS OpsWorks, seeDeploying Ruby on

AWS SDK for Ruby Developer Guide, Release 1.0

b = Aws::S3::Resource.new(region: "us-west-2").bucket(bucket)b.delete! # Recursively deletes objects as well.

Complete Example

Here is the complete code for this example.

require 'aws-sdk'

# Using Random UUIDs to Avoid Collisions when Testingrequire 'securerandom'bucket = "example-test-bucket-#{SecureRandom.uuid}"

# Setups3 = Aws::S3::Client.new(region: "us-west-2")s3.create_bucket(bucket: bucket)

# When Bucket Has No Website Configurationbegin

s3.get_bucket_website(bucket: bucket)rescue Aws::S3::Errors::NoSuchWebsiteConfiguration

puts "No bucket website configuration present."end

# Adding Simple Pages & Website Configurations3.put_object(

bucket: bucket,key: "index.html",body: "Hello, Amazon S3!",acl: "public-read"

)s3.put_object(

bucket: bucket,key: "error.html",body: "Page not found!",acl: "public-read"

)s3.put_bucket_website(

bucket: bucket,website_configuration: {

index_document: {suffix: "index.html"

},error_document: {

key: "error.html"}

})

# Accessing as a Websiteindex_path = "http://#{bucket}.s3-website-us-west-2.amazonaws.com/"

5.8. Amazon S3 Examples 101

Page 106: AWS SDK for Ruby Developer Guide … · Working with Rubyin the Elastic Beanstalk Developer Guide. For deploying a Ruby on Rails application with AWS OpsWorks, seeDeploying Ruby on

AWS SDK for Ruby Developer Guide, Release 1.0

error_path = "http://#{bucket}.s3-website-us-west-2.amazonaws.com/nonexistant.→˓html"

puts "Index Page Contents:\n#{Net::HTTP.get(URI(index_path))}\n\n"puts "Error Page Contents:\n#{Net::HTTP.get(URI(error_path))}\n\n"

# Removing Website Configurations3.delete_bucket_website(bucket: bucket)

# Cleanupb = Aws::S3::Resource.new(region: "us-west-2").bucket(bucket)b.delete! # Recursively deletes objects as well.

5.9 Amazon SNS Examples

You can use the following examples to access Amazon Simple Notification Service (Amazon SNS) usingthe AWS SDK for Ruby. For more information about Amazon SNS, see the Amazon SNS documentation.

Examples

5.9.1 Getting Information about All Topics

The following example lists the ARNs of your SNS topics in the us-west-2 region.

require 'aws-sdk'

sns = Aws::SNS::Resource.new(region: 'us-west-2')

sns.topics.each do |topic|puts topic.arn

end

5.9.2 Creating a Topic

The following example creates the topic MyGroovyTopic in the us-west-2 region and displays theresulting topic ARN.

require 'aws-sdk'

sns = Aws::SNS::Resource.new(region: 'us-west-2')

topic = sns.create_topic(name: 'MyGroovyTopic')puts topic.arn

102 Chapter 5. AWS SDK for Ruby Code Examples

Page 107: AWS SDK for Ruby Developer Guide … · Working with Rubyin the Elastic Beanstalk Developer Guide. For deploying a Ruby on Rails application with AWS OpsWorks, seeDeploying Ruby on

AWS SDK for Ruby Developer Guide, Release 1.0

5.9.3 Getting Information about All Subscriptions in a Topic

The following example lists the email addresses of the SNS subscriptions for the topic with the ARNarn:aws:sns:us-west-2:123456789:MyGroovyTopic in the us-west-2 region.

require 'aws-sdk'

sns = Aws::SNS::Resource.new(region: 'us-west-2')

topic = sns.topic('arn:aws:sns:us-west-2:123456789:MyGroovyTopic')

topic.subscriptions.each do |s|puts s.attributes['Endpoint']

end

5.9.4 Creating a Subscription in a Topic

The following example creates a subscription for the topic with the ARNarn:aws:sns:us-west-2:123456789:MyGroovyTopic for a user who has the email [email protected] in the us-west-2 region, and displays the resulting ARN. Initiallythe ARN value is pending confirmation. When the user confirms their email address, this value becomes atrue ARN.

require 'aws-sdk'

sns = Aws::SNS::Resource.new(region: 'us-west-2')

topic = sns.topic('arn:aws:sns:us-west-2:123456789:MyGroovyTopic')

sub = topic.subscribe({protocol: 'email',endpoint: '[email protected]'

})

puts sub.arn

5.9.5 Sending a Message to All Topic Subscribers

The following example sends the message “Hello!” to all subscribers to the topic with the ARNarn:aws:sns:us-west-2:123456789:MyGroovyTopic.

require 'aws-sdk'

sns = Aws::SNS::Resource.new(region: 'us-west-2')

topic = sns.topic('arn:aws:sns:us-west-2:123456789:MyGroovyTopic')

topic.publish({

5.9. Amazon SNS Examples 103

Page 108: AWS SDK for Ruby Developer Guide … · Working with Rubyin the Elastic Beanstalk Developer Guide. For deploying a Ruby on Rails application with AWS OpsWorks, seeDeploying Ruby on

AWS SDK for Ruby Developer Guide, Release 1.0

message: 'Hello!'})

5.9.6 Enabling a Resource to Publish to a Topic

The following example enables the resource with the ARN my-resource-arn to publish to the topicwith the ARN my-topic-arn in the us-west-2 region.

require 'aws-sdk'

sns = Aws::SNS::Resource.new(region: 'us-west-2')

policy = '{"Version":"2008-10-17","Id":"__default_policy_ID","Statement":[{

"Sid":"__default_statement_ID","Effect":"Allow","Principal":{

"AWS":"*"},"Action":["SNS:Publish"],"Resource":"' + my-topic-arn + '","Condition":{

"ArnEquals":{"AWS:SourceArn":"' + my-resource-arn + '"}

}}]

}'

topic.set_attributes({attribute_name: "Policy",attribute_value: policy

})

5.10 Amazon SQS Examples

You can use the following examples to access Amazon Simple Queue Service (Amazon SQS) using theAWS SDK for Ruby. For more information about Amazon SQS, see the Amazon SQS documentation.

Examples

5.10.1 Getting Information about All Queues in Amazon SQS

The following example lists the URLs, ARNs, messages available, and messages in flight of your AmazonSQS queues in the us-west-2 region.

104 Chapter 5. AWS SDK for Ruby Code Examples

Page 109: AWS SDK for Ruby Developer Guide … · Working with Rubyin the Elastic Beanstalk Developer Guide. For deploying a Ruby on Rails application with AWS OpsWorks, seeDeploying Ruby on

AWS SDK for Ruby Developer Guide, Release 1.0

require 'aws-sdk'

sqs = Aws::SQS::Client.new(region: 'us-west-2')

queues = sqs.list_queues

queues.queue_urls.each do |url|puts 'URL: ' + url

# Get ARN, messages available, and messages in flight for queuereq = sqs.get_queue_attributes(

{queue_url: url, attribute_names:

['QueueArn','ApproximateNumberOfMessages','ApproximateNumberOfMessagesNotVisible'

]}

)

arn = req.attributes['QueueArn']msgs_available = req.attributes['ApproximateNumberOfMessages']msgs_in_flight = req.attributes['ApproximateNumberOfMessagesNotVisible']

puts 'ARN: ' + arnputs 'Messages available: ' + msgs_availableputs 'Messages in flight: ' + msgs_in_flightputs

end

5.10.2 Creating a Queue in Amazon SQS

The following example creates the Amazon SQS queue MyGroovyQueue in the us-west-2 region anddisplays its URL.

require 'aws-sdk'

sqs = Aws::SQS::Client.new(region: 'us-west-2')

queue = sqs.create_queue(queue_name: 'MyGroovyQueue')

puts queue.queue_url

5.10.3 Working with Queues in Amazon SQS

Amazon SQS provides highly scalable hosted queues for storing messages as they travel betweenapplications or microservices. To learn more about queues, see How Amazon SQS Queues Work.

In this example, you use the AWS SDK for Ruby with Amazon SQS to:

5.10. Amazon SQS Examples 105

Page 110: AWS SDK for Ruby Developer Guide … · Working with Rubyin the Elastic Beanstalk Developer Guide. For deploying a Ruby on Rails application with AWS OpsWorks, seeDeploying Ruby on

AWS SDK for Ruby Developer Guide, Release 1.0

1. Get a list of your queues by using Aws::SQS::Client#list_queues.

2. Create a queue by using Aws::SQS::Client#create_queue.

3. Get the queue’s URL by using Aws::SQS::Client#get_queue_url.

4. Delete the queue by using Aws::SQS::Client#delete_queue.

Prerequisites

Before running the example code, you need to install and configure the AWS SDK for Ruby, as describedin:

• Installing the AWS SDK for Ruby

• Configuring the AWS SDK for Ruby

Example

require 'aws-sdk'

sqs = Aws::SQS::Client.new(region: 'us-east-1')

# Get a list of your queues.sqs.list_queues.queue_urls.each do |queue_url|

puts queue_urlend

# Create a queue.queue_name = "my-queue"

beginsqs.create_queue({

queue_name: queue_name,attributes: {

"DelaySeconds" => "60", # Delay message delivery for 1 minute (60→˓seconds).

"MessageRetentionPeriod" => "86400" # Delete message after 1 day (24→˓hours * 60 minutes * 60 seconds).

}})

rescue Aws::SQS::Errors::QueueDeletedRecentlyputs "A queue with the name '#{queue_name}' was recently deleted. Wait at

→˓least 60 seconds and try again."exit(false)

end

# Get the queue's URL.queue_url = sqs.get_queue_url(queue_name: queue_name).queue_urlputs queue_url

106 Chapter 5. AWS SDK for Ruby Code Examples

Page 111: AWS SDK for Ruby Developer Guide … · Working with Rubyin the Elastic Beanstalk Developer Guide. For deploying a Ruby on Rails application with AWS OpsWorks, seeDeploying Ruby on

AWS SDK for Ruby Developer Guide, Release 1.0

# Delete the queue.sqs.delete_queue(queue_url: queue_url)

5.10.4 Sending Messages in Amazon SQS

The following example sends the message “Hello world” through the Amazon SQS queue with the URLURL in the us-west-2 region.

require 'aws-sdk'

sqs = Aws::SQS::Client.new(region: 'us-west-2')

sqs.send_message(queue_url: URL, message_body: 'Hello world')

The following example sends the messages “Hello world” and “How is the weather?” through the AmazonSQS queue with the URL URL in the us-west-2 region.

require 'aws-sdk'

sqs = Aws::SQS::Client.new(region: 'us-west-2')

resp = sqs.send_message_batch({queue_url: URL,entries: [

{id: 'msg1',message_body: 'Hello world'

},{

id: 'msg2',message_body: 'How is the weather?'

}],

})

5.10.5 Sending and Receiving Messages in Amazon SQS

After you create a queue in Amazon SQS, you can send a message to it and then consume it. To learnmore, see Tutorial: Sending a Message to an Amazon SQS Queue and Tutorial: Receiving and Deleting aMessage from an Amazon SQS Queue.

In this example, you use the AWS SDK for Ruby with Amazon SQS to:

1. Send a message to a queue by using Aws::SQS::Client#send_message.

2. Receive the message in the queue by using Aws::SQS::Client#receive_message.

3. Display information about the message.

4. Delete the message from the queue by using Aws::SQS::Client#delete_message.

5.10. Amazon SQS Examples 107

Page 112: AWS SDK for Ruby Developer Guide … · Working with Rubyin the Elastic Beanstalk Developer Guide. For deploying a Ruby on Rails application with AWS OpsWorks, seeDeploying Ruby on

AWS SDK for Ruby Developer Guide, Release 1.0

Prerequisites

Before running the example code, you need to install and configure the AWS SDK for Ruby, as describedin:

• Installing the AWS SDK for Ruby

• Configuring the AWS SDK for Ruby

You also need to create the queue my-queue, which you can do in the Amazon SQS console.

Example

require 'aws-sdk'

sqs = Aws::SQS::Client.new(region: 'us-east-1')

# Send a message to a queue.queue_name = "my-queue"

beginqueue_url = sqs.get_queue_url(queue_name: queue_name).queue_url

# Create a message with three custom attributes: Title, Author, and WeeksOn.send_message_result = sqs.send_message({

queue_url: queue_url,message_body: "Information about current NY Times fiction bestseller for

→˓week of 2016-12-11.",message_attributes: {

"Title" => {string_value: "The Whistler",data_type: "String"

},"Author" => {

string_value: "John Grisham",data_type: "String"

},"WeeksOn" => {

string_value: "6",data_type: "Number"

}}

})rescue Aws::SQS::Errors::NonExistentQueue

puts "A queue named '#{queue_name}' does not exist."exit(false)

end

puts send_message_result.message_id

# Receive the message in the queue.receive_message_result = sqs.receive_message({

queue_url: queue_url,

108 Chapter 5. AWS SDK for Ruby Code Examples

Page 113: AWS SDK for Ruby Developer Guide … · Working with Rubyin the Elastic Beanstalk Developer Guide. For deploying a Ruby on Rails application with AWS OpsWorks, seeDeploying Ruby on

AWS SDK for Ruby Developer Guide, Release 1.0

message_attribute_names: ["All"], # Receive all custom attributes.max_number_of_messages: 1, # Receive at most one message.wait_time_seconds: 0 # Do not wait to check for the message.

})

# Display information about the message.# Display the message's body and each custom attribute value.receive_message_result.messages.each do |message|

puts message.bodyputs "Title: #{message.message_attributes["Title"]["string_value"]}"puts "Author: #{message.message_attributes["Author"]["string_value"]}"puts "WeeksOn: #{message.message_attributes["WeeksOn"]["string_value"]}"

# Delete the message from the queue.sqs.delete_message({

queue_url: queue_url,receipt_handle: message.receipt_handle

})end

5.10.6 Receiving Messages in Amazon SQS

The following example displays the body of up to 10 messages in the Amazon SQS queue with the URLURL in the us-west-2 region.

Note: receive_message does not guarantee to get all messages (see Properties of DistributedQueues), and by default does not delete the message.

require 'aws-sdk'

sqs = Aws::SQS::Client.new(region: 'us-west-2')

resp = sqs.receive_message(queue_url: URL, max_number_of_messages: 10)

resp.messages.each do |m|puts m.body

end

5.10.7 Receiving Messages Using Long Polling in Amazon SQS

The following example waits up to 10 seconds to display the bodies of up to 10 messages in the AmazonSQS queue with the URL URL in the us-west-2 region.

If you do not specify a wait time, the default value is 0 (Amazon SQS does not wait).

require 'aws-sdk'

sqs = Aws::SQS::Client.new(region: 'us-west-2')

5.10. Amazon SQS Examples 109

Page 114: AWS SDK for Ruby Developer Guide … · Working with Rubyin the Elastic Beanstalk Developer Guide. For deploying a Ruby on Rails application with AWS OpsWorks, seeDeploying Ruby on

AWS SDK for Ruby Developer Guide, Release 1.0

resp = sqs.receive_message(queue_url: URL, max_number_of_messages: 10, wait_→˓time_seconds: 10)

resp.messages.each do |m|puts m.body

end

5.10.8 Enabling Long Polling in Amazon SQS

Long polling helps lower your cost of using Amazon SQS by reducing the number of empty responses andeliminating false empty responses. For more information about long polling, see Amazon SQS LongPolling.

In this example, you use the AWS SDK for Ruby with Amazon SQS to:

1. Create a queue and set it for long polling by using Aws::SQS::Client#create_queue.

2. Set long polling for an existing queue by using Aws::SQS::Client#set_queue_attributes.

3. Set long polling when receiving messages for a queue by using Aws::SQS::Client#receive_message.

Prerequisites

Before running the example code, you need to install and configure the AWS SDK for Ruby, as describedin:

• Installing the AWS SDK for Ruby

• Configuring the AWS SDK for Ruby

You also need to create the queues existing-queue and receive-queue, which you can do in the AmazonSQS console.

Example

require 'aws-sdk'

sqs = Aws::SQS::Client.new(region: 'us-east-1')

# Create a queue and set it for long polling.new_queue_name = "new-queue"

create_queue_result = sqs.create_queue({queue_name: new_queue_name,attributes: {

"ReceiveMessageWaitTimeSeconds" => "20" # Wait 20 seconds to receive→˓messages.},

})

110 Chapter 5. AWS SDK for Ruby Code Examples

Page 115: AWS SDK for Ruby Developer Guide … · Working with Rubyin the Elastic Beanstalk Developer Guide. For deploying a Ruby on Rails application with AWS OpsWorks, seeDeploying Ruby on

AWS SDK for Ruby Developer Guide, Release 1.0

puts create_queue_result.queue_url

# Set long polling for an existing queue.begin

existing_queue_name = "existing-queue"existing_queue_url = sqs.get_queue_url(queue_name: existing_queue_name).

→˓queue_url

sqs.set_queue_attributes({queue_url: existing_queue_url,attributes: {

"ReceiveMessageWaitTimeSeconds" => "20" # Wait 20 seconds to receive→˓messages.

},})

rescue Aws::SQS::Errors::NonExistentQueueputs "Cannot set long polling for a queue named '#{existing_queue_name}',

→˓as it does not exist."end

# Set long polling when receiving messages for a queue.

# 1. Using receive_message.begin

receive_queue_name = "receive-queue"receive_queue_url = sqs.get_queue_url(queue_name: receive_queue_name).queue_

→˓url

puts "Begin receipt of any messages using receive_message..."receive_message_result = sqs.receive_message({

queue_url: receive_queue_url,attribute_names: ["All"], # Receive all available built-in message

→˓attributes.message_attribute_names: ["All"], # Receive any custom message attributes.max_number_of_messages: 10 # Receive up to 10 messages, if there are that

→˓many.})

puts "Received #{receive_message_result.messages.count} message(s)."rescue Aws::SQS::Errors::NonExistentQueue

puts "Cannot receive messages using receive_message for a queue named '#→˓{receive_queue_name}', as it does not exist."end

# 2. Using Aws::SQS::QueuePoller.begin

puts "Begin receipt of any messages using Aws::SQS::QueuePoller..."puts "(Will keep polling until no more messages available for at least 60

→˓seconds.)"poller = Aws::SQS::QueuePoller.new(receive_queue_url)

poller_stats = poller.poll({

5.10. Amazon SQS Examples 111

Page 116: AWS SDK for Ruby Developer Guide … · Working with Rubyin the Elastic Beanstalk Developer Guide. For deploying a Ruby on Rails application with AWS OpsWorks, seeDeploying Ruby on

AWS SDK for Ruby Developer Guide, Release 1.0

max_number_of_messages: 10,idle_timeout: 60 # Stop polling after 60 seconds of no more messages

→˓available (polls indefinitely by default).}) do |messages|

messages.each do |message|puts "Message body: #{message.body}"

endend# Note: If poller.poll is successful, all received messages are

→˓automatically deleted from the queue.

puts "Poller stats:"puts " Polling started at: #{poller_stats.polling_started_at}"puts " Polling stopped at: #{poller_stats.polling_stopped_at}"puts " Last message received at: #{poller_stats.last_message_received_at}"puts " Number of polling requests: #{poller_stats.request_count}"puts " Number of received messages: #{poller_stats.received_message_count}"

rescue Aws::SQS::Errors::NonExistentQueueputs "Cannot receive messages using Aws::SQS::QueuePoller for a queue named

→˓'#{receive_queue_name}', as it does not exist."end

5.10.9 Receiving Messages Using the QueuePoller Class in Amazon SQS

The following example uses the QueuePoller utility class to display the body of all messages in theSQS queue with the URL URL in the us-west-2 region, and deletes the message. After approximately15 seconds of inactivity, the script times out.

require 'aws-sdk'

Aws.config.update({region: 'us-west-2'})

poller = Aws::SQS::QueuePoller.new(URL)

poller.poll(idle_timeout: 15) do |msg|puts msg.body

end

The following example loops through the Amazon SQS queue with the URL URL, and waits up to durationseconds.

You can get the correct URL by executing the Amazon SQS example in Getting Information about AllQueues in Amazon SQS.

require 'aws-sdk'

Aws.config.update({region: 'us-west-2'})

poller = Aws::SQS::QueuePoller.new(URL)

poller.poll(wait_time_seconds: duration, idle_timeout: duration + 1) do |msg|

112 Chapter 5. AWS SDK for Ruby Code Examples

Page 117: AWS SDK for Ruby Developer Guide … · Working with Rubyin the Elastic Beanstalk Developer Guide. For deploying a Ruby on Rails application with AWS OpsWorks, seeDeploying Ruby on

AWS SDK for Ruby Developer Guide, Release 1.0

puts msg.bodyend

The following example loops through the Amazon SQS queue with the URL URL, and gives you up to thevisibility timeout seconds to process the message, represented by the method do_something.

require 'aws-sdk'

# Process the messagedef do_something(msg)

puts msg.bodyend

Aws.config.update({region: 'us-west-2'})

poller = Aws::SQS::QueuePoller.new(URL)

poller.poll(timeout_visibility: timeout, idle_timeout: timeout + 1) do |msg|do_something(msg)

end

The following example loops through the Amazon SQS queue with the URL URL, and changes thevisibility timeout seconds, for any message that needs additional processing by the methoddo_something2.

require 'aws-sdk'

# Process the messagedef do_something(msg)

trueend

# Do additional processingdef do_something2(msg)

puts msg.bodyend

Aws.config.update({region: 'us-west-2'})

poller = Aws::SQS::QueuePoller.new(URL)

poller.poll(idle_timeout: timeout + 1) do |msg|if do_something(msg)

# need more time for processingpoller.change_message_visibility_timeout(msg, timeout)

do_something2(msg)end

end

5.10. Amazon SQS Examples 113

Page 118: AWS SDK for Ruby Developer Guide … · Working with Rubyin the Elastic Beanstalk Developer Guide. For deploying a Ruby on Rails application with AWS OpsWorks, seeDeploying Ruby on

AWS SDK for Ruby Developer Guide, Release 1.0

5.10.10 Redirecting Dead Letters in Amazon SQS

The following example redirects any dead letters from the queue with the URL URL to the queue with theARN ARN.

require 'aws-sdk'

sqs = Aws::SQS::Client.new(region: 'us-west-2')

sqs.set_queue_attributes({queue_url: URL,attributes:

{'RedrivePolicy' => "{\"maxReceiveCount\":\"5\", \"deadLetterTargetArn\":

→˓\"#{ARN}\"}"}

})

5.10.11 Deleting a Queue in Amazon SQS

The following example deletes the Amazon SQS queue with the URL URL in the us-west-2 region.

require 'aws-sdk'

sqs = Aws::SQS::Client.new(region: 'us-west-2')

sqs.delete_queue(queue_url: URL)

5.10.12 Enabling a Resource to Publish to a Queue in Amazon SQS

The following example enables the resource with the ARN my-resource-arn to publish to the queuewith the ARN my-queue-arn and URL my-queue-url in the us-west-2 region.

require 'aws-sdk'

sqs = Aws::SQS::Client.new(region: 'us-west-2')

policy = '{"Version":"2008-10-17","Id":' + my-queue-arn + '/SQSDefaultPolicy","Statement":[{

"Sid":"__default_statement_ID","Effect":"Allow","Principal":{

"AWS":"*"},"Action":["SQS:SendMessage"],"Resource":"' + my-queue-arn + '","Condition":{

"ArnEquals":{

114 Chapter 5. AWS SDK for Ruby Code Examples

Page 119: AWS SDK for Ruby Developer Guide … · Working with Rubyin the Elastic Beanstalk Developer Guide. For deploying a Ruby on Rails application with AWS OpsWorks, seeDeploying Ruby on

AWS SDK for Ruby Developer Guide, Release 1.0

"AWS:SourceArn":"' + my-resource-arn + '"}}

}]}'

sqs.set_queue_attributes({queue_url: my-queue-url,attributes: {

Policy: policy}

})

5.10.13 Working with a Dead Letter Queue in Amazon SQS

Amazon SQS provides support for dead letter queues. A dead letter queue is a queue that other (source)queues can target for messages that can’t be processed successfully. You can set aside and isolate thesemessages in the dead letter queue to determine why their processing didn’t succeed. For more informationabout dead letter queues, see Using Amazon SQS Dead Letter Queues.

In this example, you use the AWS SDK for Ruby with Amazon SQS to:

1. Create a queue that represents a dead letter queue by using Aws::SQS::Client#create_queue.

2. Associate the dead letter queue with an existing queue by usingAws::SQS::Client#set_queue_attributes.

3. Send a message to the existing queue by using Aws::SQS::Client#send_message.

4. Poll the queue by using Aws::SQS::QueuePoller.

5. Receive messages in the dead letter queue by using Aws::SQS::Client#receive_message.

Prerequisites

Before running the example code, you need to install and configure the AWS SDK for Ruby, as describedin:

• Installing the AWS SDK for Ruby

• Configuring the AWS SDK for Ruby

You also need to use the AWS Management Console to create the existing queue, my-queue.

Example

require 'aws-sdk'

# Uncomment for Windows.# Aws.use_bundled_cert!

sqs = Aws::SQS::Client.new(region: 'us-east-1')

5.10. Amazon SQS Examples 115

Page 120: AWS SDK for Ruby Developer Guide … · Working with Rubyin the Elastic Beanstalk Developer Guide. For deploying a Ruby on Rails application with AWS OpsWorks, seeDeploying Ruby on

AWS SDK for Ruby Developer Guide, Release 1.0

# Create a queue representing a dead letter queue.dead_letter_queue_name = "dead-letter-queue"

sqs.create_queue({queue_name: dead_letter_queue_name

})

# Get the dead letter queue's URL and ARN, so that you can associate it with→˓an existing queue.dead_letter_queue_url = sqs.get_queue_url(queue_name: dead_letter_queue_name).→˓queue_url

dead_letter_queue_arn = sqs.get_queue_attributes({queue_url: dead_letter_queue_url,attribute_names: ["QueueArn"]

}).attributes["QueueArn"]

# Associate the dead letter queue with an existing queue.begin

queue_name = "my-queue"queue_url = sqs.get_queue_url(queue_name: queue_name).queue_url

# Use a redrive policy to specify the dead letter queue and its behavior.redrive_policy = {

"maxReceiveCount" => "5", # After the queue receives the same message 5→˓times, send that message to the dead letter queue.

"deadLetterTargetArn" => dead_letter_queue_arn}.to_json

sqs.set_queue_attributes({queue_url: queue_url,attributes: {

"RedrivePolicy" => redrive_policy}

})

rescue Aws::SQS::Errors::NonExistentQueueputs "A queue named '#{queue_name}' does not exist."exit(false)

end

# Send a message to the queue.puts "Sending a message..."

sqs.send_message({queue_url: queue_url,message_body: "I hope I get moved to the dead letter queue."

})

30.downto(0) do |i|print "\rWaiting #{i} second(s) for sent message to be receivable..."sleep(1)

116 Chapter 5. AWS SDK for Ruby Code Examples

Page 121: AWS SDK for Ruby Developer Guide … · Working with Rubyin the Elastic Beanstalk Developer Guide. For deploying a Ruby on Rails application with AWS OpsWorks, seeDeploying Ruby on

AWS SDK for Ruby Developer Guide, Release 1.0

end

puts "\n"

poller = Aws::SQS::QueuePoller.new(queue_url)# Receive 5 messages max and stop polling after 20 seconds of no received→˓messages.poller.poll(max_number_of_messages:5, idle_timeout: 20) do |messages|

messages.each do |msg|puts "Received message ID: #{msg.message_id}"

endend

# Check to see if Amazon SQS moved the message to the dead letter queue.receive_message_result = sqs.receive_message({

queue_url: dead_letter_queue_url,max_number_of_messages: 1

})

if receive_message_result.messages.count > 0puts "\n#{receive_message_result.messages[0].body}"

elseputs "\nNo messages received."

end

5.10.14 Specifying the Message Visibility Timeout in Amazon SQS

In Amazon SQS, immediately after a message is received, it remains in the queue. To prevent otherconsumers from processing the message again, Amazon SQS sets a visibility timeout. This is a period oftime during which Amazon SQS prevents other consuming components from receiving and processing themessage. To learn more, see Visibility Timeout.

In this example, you use the AWS SDK for Ruby with Amazon SQS to:

1. Get the URL of an existing queue by using Aws::SQS::Client#get_queue_url.

2. Receive up to 10 messages by using Aws::SQS::Client#receive_message.

3. Specify the time interval during which messages are not visible after they are received, by usingAws::SQS::Client#change_message_visibility.

Prerequisites

Before running the example code, you need to install and configure the AWS SDK for Ruby, as describedin:

• Installing the AWS SDK for Ruby

• Configuring the AWS SDK for Ruby

You also need to create the queue my-queue, which you can do in the Amazon SQS console.

5.10. Amazon SQS Examples 117

Page 122: AWS SDK for Ruby Developer Guide … · Working with Rubyin the Elastic Beanstalk Developer Guide. For deploying a Ruby on Rails application with AWS OpsWorks, seeDeploying Ruby on

AWS SDK for Ruby Developer Guide, Release 1.0

Example

require 'aws-sdk'

sqs = Aws::SQS::Client.new(region: 'us-east-1')

beginqueue_name = "my-queue"queue_url = sqs.get_queue_url(queue_name: queue_name).queue_url

receive_message_result_before = sqs.receive_message({queue_url: queue_url,max_number_of_messages: 10 # Receive up to 10 messages, if there are that

→˓many.})

puts "Before attempting to change message visibility timeout: received #→˓{receive_message_result_before.messages.count} message(s)."

receive_message_result_before.messages.each do |message|sqs.change_message_visibility({

queue_url: queue_url,receipt_handle: message.receipt_handle,visibility_timeout: 36000 # This message will not be visible for 10

→˓hours (10 hours * 60 minutes * 60 seconds) after first receipt.})

end

# Try to retrieve the original messages after setting their visibility→˓timeout.receive_message_result_after = sqs.receive_message({

queue_url: queue_url,max_number_of_messages: 10

})

puts "\nAfter attempting to change message visibility timeout: received #→˓{receive_message_result_after.messages.count} message(s)."

rescue Aws::SQS::Errors::NonExistentQueueputs "Cannot receive messages for a queue named '#{receive_queue_name}', as

→˓it does not exist."end

118 Chapter 5. AWS SDK for Ruby Code Examples

Page 123: AWS SDK for Ruby Developer Guide … · Working with Rubyin the Elastic Beanstalk Developer Guide. For deploying a Ruby on Rails application with AWS OpsWorks, seeDeploying Ruby on

CHAPTER 6

AWS SDK for Ruby Tips and Tricks

This section provides tips and tricks on using the AWS SDK for Ruby with AWS services.

6.1 Amazon EC2 Tips and Tricks

This section provides some tips to help you the AWS SDK for Ruby with Amazon Elastic Compute Cloud(Amazon EC2) services. For more information about Amazon EC2, see the Amazon EC2 Getting StartedGuide.

6.1.1 Switching Elastic IPs

The following example associates the Elastic IP address with the instance represented by i-12345678.

ec2 = Aws::EC2::Client.new

resp = ec2.allocate_addressec2.associate_address(instance_id:"i-12345678", allocation_id: resp.→˓allocation_id)

119

Page 124: AWS SDK for Ruby Developer Guide … · Working with Rubyin the Elastic Beanstalk Developer Guide. For deploying a Ruby on Rails application with AWS OpsWorks, seeDeploying Ruby on

AWS SDK for Ruby Developer Guide, Release 1.0

120 Chapter 6. AWS SDK for Ruby Tips and Tricks

Page 125: AWS SDK for Ruby Developer Guide … · Working with Rubyin the Elastic Beanstalk Developer Guide. For deploying a Ruby on Rails application with AWS OpsWorks, seeDeploying Ruby on

CHAPTER 7

Document History

To view the list of changes to the AWS SDK for Ruby and its documentation, see the CHANGELOG.mdfile in the aws/aws-sdk-ruby repository in GitHub.

121

Page 126: AWS SDK for Ruby Developer Guide … · Working with Rubyin the Elastic Beanstalk Developer Guide. For deploying a Ruby on Rails application with AWS OpsWorks, seeDeploying Ruby on

AWS SDK for Ruby Developer Guide, Release 1.0

122 Chapter 7. Document History

Page 127: AWS SDK for Ruby Developer Guide … · Working with Rubyin the Elastic Beanstalk Developer Guide. For deploying a Ruby on Rails application with AWS OpsWorks, seeDeploying Ruby on

CHAPTER 8

About Amazon Web Services

Amazon Web Services (AWS) is a collection of digital infrastructure services that developers can leveragewhen developing their applications. The services include computing, storage, database, and applicationsynchronization (messaging and queuing). AWS uses a pay-as-you-go service model: you are charged onlyfor the services that you—or your applications—use. For new AWS users, a free usage tier is available. Onthis tier, services are free below a certain level of usage. For more information about AWS costs and theFree Tier, see Use the AWS Free Tier. To obtain an AWS account, visit the AWS home page and clickCreate a Free Account.

123