Download AWS SDK for Ruby Developer Guide

Document related concepts
no text concepts found
Transcript
AWS SDK for Ruby Developer Guide
May 08, 2017
Contents
AWS SDK for Ruby Developer Guide
AWS SDK for Ruby Developer Guide
1
2
About This Guide
2
Additional Documentation and Resources
2
Deploying to the AWS Cloud
Getting Started with the AWS SDK for Ruby
QuickStart Guide to Using the AWS SDK for Ruby
3
4
4
Write the Code
4
Run the Code
4
Note for Windows users
4
Installing the AWS SDK for Ruby
5
Prerequisites
To sign up for AWS
Installing the AWS SDK for Ruby
Configuring the AWS SDK for Ruby
Setting AWS Credentials
5
5
5
5
5
Setting Shared Credentials
6
Setting Credentials Using Environment Variables
6
Setting Credentials Using Aws.config
6
Setting Credentials in a Client Object
7
Setting Credentials Using IAM
7
Creating an AWS STS Access Token
7
Setting a Region
7
Setting the Region Using Environment Variables
7
Setting the Region Using Aws.config
8
Setting the Region in a Client or Resource Object
8
Setting a Nonstandard Endpoint
8
Using the AWS SDK for Ruby REPL
8
Using the SDK with Ruby on Rails
9
Integrating the AWS SDK for Ruby with Rails
9
Amazon SES Support for ActionMailer
9
Logging
9
Migrating from version 1 to version 2 of the AWS SDK for Ruby
10
Side-by-Side Usage
10
General Differences
10
Client Differences
10
Resource Differences
11
Hello World Tutorial
13
Using the AWS SDK for Ruby in Your Program
13
Creating an Amazon S3 Resource
13
Creating a Bucket
13
Adding a File to the Bucket
13
Listing the Contents of a Bucket
13
Complete Program
14
Running the Program
16
Next Steps
16
Programming with the AWS SDK for Ruby
17
Debugging Tip: Getting Wire Trace Information from a Client
17
Stubbing Client Responses and Errors
18
Stubbing Client Responses
18
Stubbing Client Errors
19
Paging Response Data
19
Paged Responses Are Enumerable
19
Handling Paged Responses Manually
20
Paged Data Classes
20
Using Waiters
20
Invoking a Waiter
20
Wait Failures
21
Configuring a Waiter
21
Extending a Waiter
22
Specifying a Client Timeout Duration
22
AWS SDK for Ruby Code Examples
23
Amazon CloudWatch Examples
23
Getting Information about All Alarms
23
Creating an Alarm
23
Enabling and Disabling Alarm Actions
24
Prerequisites
25
Example
25
Getting Info about Custom Metrics
26
Prerequisites
26
Example
26
Sending Events to Amazon CloudWatch Events
27
Prerequisites
28
Example
28
Amazon DynamoDB Examples
31
Getting Information about All Tables
31
Creating a Simple Table with a Single Primary Key
31
Adding an Item to a Table
32
Getting Information about the Items in a Table
33
Getting Information about a Specific Item in a Table
33
Updating a Table
33
Creating an Index
34
Amazon EC2 Examples
35
Creating a VPC
35
Creating an Internet Gateway and Attaching It to a VPC
35
Creating a Public Subnet
36
Creating a Route Table and Associating It with a Subnet
36
Using Elastic IP Addresses in Amazon EC2
37
Prerequisites
37
Example Script
38
Creating a Security Group
39
Working with Security Groups in Amazon EC2
39
Prerequisites
40
Configure the SDK
40
Create a Security Group
40
Get Info about a Security Group
41
Delete a Security Group
43
Working with Key Pairs
43
Create a Key Pair
43
Get Information about Key Pairs
44
Delete a Key Pair
44
Complete Example
45
Getting Information about All Instances
46
Getting Information about All Instances with a Specific Tag Value
46
Getting Information about a Specific Instance
47
Creating an Instance
47
Stopping an Instance
48
Starting an Instance
48
Rebooting an Instance
49
Managing Amazon EC2 Instances in Amazon EC2
49
Prerequisites
49
Example
50
Terminating an Instance
51
Getting Information about Regions and Availability Zones
52
Get Information about Regions and Endpoints
52
Get Information about Availability Zones
52
Complete Example
53
AWS Elastic Beanstalk Examples
54
Getting Information about All Applications
54
Getting Information about a Specific Application
54
Updating a Ruby on Rails Application
54
AWS Identity and Access Management Examples
56
Getting Information about All Users
56
Adding a New User
57
Create a User's Access Keys
57
Adding a Managed Policy
58
Creating a Role
58
Managing IAM Users
59
Prerequisites
59
Example
59
Working with IAM Policies
60
Prerequisites
61
Example
61
Managing IAM Access Keys
62
Prerequisites
62
Example
62
Working with IAM Server Certificates
Prerequisites
64
64
Example
Managing IAM Account Aliases
64
65
Prerequisites
65
Example
65
Lambda Examples
66
Displaying Information about All Lambda Functions
66
Creating a Lambda Function
67
Configuring a Lambda Function to Receive Notifications
67
Amazon Relational Database Service Examples
68
Getting Information about All Instances
68
Getting Information about All Snapshots
68
Getting Information about All Clusters and Their Snapshots
69
Getting Information about All Security Groups
69
Getting Information about All Subnet Groups
70
Getting Information about All Parameter Groups
70
Creating a Snapshot of an Instance
70
Creating a Snapshot of a Cluster
71
Amazon S3 Examples
71
Getting Information about All Buckets
72
Getting Information about All Buckets in a Region
72
Creating and Using an Amazon S3 Bucket
73
Prerequisite Tasks
73
Configure the SDK
73
Get a List of Buckets
74
Create a Bucket
74
Upload an Object (a File) to a Bucket
74
Copy Files between Buckets
74
Delete Files from a Bucket
75
Complete Example
75
Alternative Approaches
77
Determining Whether a Bucket Exists
77
Getting Information about Bucket Items
78
Uploading an Item to a Bucket
78
Uploading an Item with Metadata to a Bucket
78
Downloading an Object from a Bucket into a File
79
Changing the Properties for a Bucket Item
79
Triggering a Notification When an Item is Added to a Bucket
80
Enabling Amazon S3 to Send a Notification
80
Creating an Amazon S3 Bucket Notification
81
Creating a Bucket LifeCycle Rule Configuration Template
82
Creating a Bucket Policy with Ruby
84
Prerequisite Tasks
84
Configure the SDK
84
Create a Bucket
85
Define a Bucket Policy
85
Add the Policy to the Bucket
86
Change the Policy
86
Clean Up
86
Complete Example
86
Configuring a Bucket for Cross-Origin Resource Sharing (CORS)
87
Prerequisite Tasks
88
Configure the SDK
88
Configure CORS for a Bucket
88
Get the CORS Settings for a Bucket
89
Complete Example
90
Managing Amazon S3 Bucket and Object Access Permissions
91
Prerequisite Tasks
91
Configure the SDK
91
Set a Canned ACL for a Bucket
92
Upload an Object to a Bucket
92
Set a Canned ACL for an Object
92
Get a Bucket's Current ACL
93
Complete Example
93
Using a Amazon S3 Bucket to Host a Website
94
Prerequisite Tasks
94
Configure the SDK
95
Create a Bucket
95
Get a Bucket Website's Configuration
95
Add an Object to a Bucket
95
Set a Bucket Website's Configuration
96
Access a Bucket Website's Documents
96
Delete a Bucket Website
96
Delete a Bucket
96
Complete Example
97
Amazon SNS Examples
98
Getting Information about All Topics
98
Creating a Topic
98
Getting Information about All Subscriptions in a Topic
98
Creating a Subscription in a Topic
99
Sending a Message to All Topic Subscribers
99
Enabling a Resource to Publish to a Topic
99
Amazon SQS Examples
100
Getting Information about All Queues in Amazon SQS
100
Creating a Queue in Amazon SQS
101
Working with Queues in Amazon SQS
101
Prerequisites
101
Example
102
Sending Messages in Amazon SQS
102
Sending and Receiving Messages in Amazon SQS
103
Prerequisites
103
Example
103
Receiving Messages in Amazon SQS
105
Receiving Messages Using Long Polling in Amazon SQS
105
Enabling Long Polling in Amazon SQS
105
Prerequisites
106
Example
106
Receiving Messages Using the QueuePoller Class in Amazon SQS
107
Redirecting Dead Letters in Amazon SQS
109
Deleting a Queue in Amazon SQS
109
Enabling a Resource to Publish to a Queue in Amazon SQS
110
Working with a Dead Letter Queue in Amazon SQS
110
Prerequisites
111
Example
111
Specifying the Message Visibility Timeout in Amazon SQS
Prerequisites
112
113
Example
113
AWS SDK for Ruby Tips and Tricks
115
Amazon EC2 Tips and Tricks
115
Switching Elastic IPs
115
Document History
116
About Amazon Web Services
117
AWS SDK for Ruby Developer Guide
AWS SDK for Ruby Developer Guide
1
AWS SDK for Ruby Developer Guide
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 all AWS
services, including Amazon Simple Storage Service, Amazon Elastic Compute Cloud, and Amazon
DynamoDB. For a complete list of services supported by the AWS SDK for Ruby, see the Supported Services
section of the AWS SDK for Ruby Readme file.
About This Guide
The AWS SDK for Ruby Developer Guide provides information about how to install, set up, and use the AWS
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 with the AWS SDK for Ruby.
AWS SDK for Ruby Code Examples
Provides code examples that developers can use to program AWS services with the AWS SDK for Ruby.
Document History
Describes the history of this document.
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
• @awsforruby on Twitter
• On GitHub:
• Releases (includes source, gems, and documentation)
• Source
• Change log
• Migration Guide
• Issues
• Feature requests
• Upgrading notes
2
AWS SDK for Ruby Developer Guide
Deploying to the AWS Cloud
You can use AWS services such as AWS Elastic Beanstalk, AWS OpsWorks, and AWS CodeDeploy to
deploy your application to the AWS Cloud. For deploying Ruby applications with Elastic Beanstalk, see
Working with Ruby in the Elastic Beanstalk Developer Guide. For deploying a Ruby on Rails application with
AWS OpsWorks, see Deploying Ruby on Rails Applications to AWS OpsWorks. For an overview of AWS
deployment services, see Overview of Deployment Options on AWS.
3
Getting Started with the AWS SDK for Ruby
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 about
installing, setting up, and using the SDK to create a Ruby application to access Amazon S3.
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 lists your
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.
Write the Code
The following example lists the names of up to 50 of your buckets. Copy the code and save it as buckets.rb.
Note 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.
require 'aws-sdk'
s3 = Aws::S3::Resource.new(region: 'us-west-2')
s3.buckets.limit(50).each do |b|
puts "#{b.name}"
end
Run the Code
Enter the following command to execute buckets.rb.
ruby buckets.rb
Note for Windows users
When you use SSL certificates on Windows and run your Ruby code, you will see an error similar to the
following.
C:\Ruby>ruby buckets.rb
C:/Ruby200-x64/lib/ruby/2.0.0/net/http.rb:921:in `connect': SSL_connect returned=1 errno=0
from C:/Ruby200-x64/lib/ruby/2.0.0/net/http.rb:921:in `block in connect'
from
from
from
from
C:/Ruby200-x64/lib/ruby/2.0.0/timeout.rb:66:in `timeout'
C:/Ruby200-x64/lib/ruby/2.0.0/net/http.rb:921:in `connect'
C:/Ruby200-x64/lib/ruby/2.0.0/net/http.rb:862:in `do_start'
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.
4
Getting Started with the AWS SDK for Ruby
Aws.use_bundled_cert!
Installing the AWS SDK for Ruby
This section includes prerequisites and installation instructions.
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.
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 to your
project.
gem aws-sdk
If you don't use Bundler, the easiest way to install the SDK is to use RubyGems. To install the latest version of
the SDK, use the following command.
gem install aws-sdk
If the previous command fails on your Unix-based system, use sudo to install the SDK, as shown in the
following command.
sudo gem install aws-sdk
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 or
create an AWS STS access token, and set the AWS Region you want to use.
Setting AWS Credentials
Before you can use the AWS SDK for Ruby to make a call to an AWS service, you must set the AWS access
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
5
Getting Started with the AWS SDK for Ruby
4. Setting Shared Credentials
5. Setting Credentials Using IAM
The following sections describe the various ways you can set credentials, starting with the most flexible
approach. For more information about AWS credentials and recommended approaches for credential
management, 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 profile given
to these credentials, your_access_key_id is the value of your access key, and
your_secret_access_key is the value of your secret access key.
[default]
aws_access_key_id = your_access_key_id
aws_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. The
following example sets the value of your access key to your_access_key_id and the value of your secret
access key to your_secret_access_key.
export AWS_ACCESS_KEY_ID=your_access_key_id
export 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_id
set 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 of your
secret access key to your_secret_access_key. Any client or resource you create subsequently will use
these credentials.
6
Getting Started with the AWS SDK for Ruby
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 and the
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'
)
Setting Credentials Using IAM
For an Amazon Elastic Compute Cloud instance, create an IAM role, and then give your Amazon EC2
instance access to that role. For more information, see IAM Roles for Amazon EC2 in the Amazon EC2 User
Guide for Linux Instances or IAM Roles for Amazon EC2 in the Amazon EC2 User Guide for Windows Instances.
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, where
linked::account::arn is the Amazon Resource Name (ARN) of the role to assume and session-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)
Setting a Region
You need to set a region when using most AWS services. You can set the AWS Region in ways similar to
setting 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
7
Getting Started with the AWS SDK for Ruby
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. The following
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 to
us-west-2.
set AWS_REGION=us-west-2
Setting the Region Using Aws.config
Set the region by adding a region value to the Aws.config hash. The following example updates the
Aws.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 S3
resource object in the us-west-1 region.
s3 = Aws::S3::Resource.new(region: 'us-west-1')
Setting a Nonstandard Endpoint
If you need to use a nonstandard endpoint in the region you've selected, add an endpoint entry to
Aws.config or set the endpoint: when creating a service client or resource object. The following example
creates an Amazon S3 resource object in the other_endpoint endpoint.
s3 = Aws::S3::Resource.new(endpoint: other_endpoint)
Using the AWS SDK for Ruby REPL
Developers can use aws.rb, the interactive command-line read-evaluate-print loop (REPL) console tool that
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.
8
Getting Started with the AWS SDK for Ruby
aws.rb
aws.rb -v
The second command line invokes the REPL with extensive HTTP wire logging, which provides information
about the communication between the AWS SDK for Ruby and AWS. Use this command line with 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 the
name of the helper object. For example, the names of the Amazon S3 and Amazon EC2 helper objects are s3
and ec2, respectively.
Using the SDK with Ruby on Rails
Ruby on Rails provides a web development framework for Ruby that makes it easy to create websites with
Ruby.
The AWS SDK for Ruby provides a gem to enable easy integration with Rails. You can use AWS Elastic
Beanstalk, AWS OpsWorks, or AWS CodeDeploy to deploy and run your Rails applications in the AWS
Cloud.
Integrating the AWS SDK for Ruby with Rails
AWS provides a gemfile, aws-sdk-rails, that supports integration of the AWS SDK for Ruby with Rails.
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 to
your Rails application.
Amazon SES Support for ActionMailer
When you use the aws-sdk-rails gem in a config/environments file of your Rails project (for example,
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.
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 level by
setting :log_level in the Aws.config hash. The following example sets the log level to :debug.
Aws.config.update({log_level: :debug})
9
Getting Started with the AWS SDK for Ruby
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.
Side-by-Side Usage
It is not necessary to replace the version 1 AWS SDK for Ruby with version 2. You can use them together in
the same application. See this blog post for more information.
A quick example follows:
require 'aws-sdk-v1' # version 1
require 'aws-sdk'
# version 2
s3 = AWS::S3::Client.new # version 1
s3 = 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 valid migration
strategy is to only write new code against the version 2 SDK.
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 an ArgumentError.
For example:
# version 1
AWS::S3::Client.new(http_reed_timeout: 10)
# oops, typo'd option is ignored
# version 2
Aws::S3::Client.new(http_reed_timeout: 10)
# => raises ArgumentError
Client Differences
Between version 1 and version 2, the client classes have the fewest external differences. Many service clients
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 is generated
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 1
resp = AWS::EC2::Client.new.describe_security_groups
10
Getting Started with the AWS SDK for Ruby
resp.security_group_set
#=> [...]
# version 2
resp = Aws::EC2::Client.new.describe_security_groups
resp.security_groups
#=> [...]
• Aws::SWF::Client - Version two uses structured responses, where version 1 uses vanilla Ruby
hashes.
• 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 in version
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 must configure
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
Resource Differences
There are significant differences between the resource interfaces in version 1 and version 2. Version 1 was
entirely hand-coded, where as version 2 resource interfaces are generated from a model. Version 2 resource
interfaces 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 is
the resource interface:
# version 1
s3 = AWS::S3.new
# version 2
s3 = Aws::S3::Resource.new
• Referencing resources - The version 2 SDK separates collections and individual resource getters into
two different methods:
11
Getting Started with the AWS SDK for Ruby
# version 1
s3.buckets['bucket-name'].objects['key'].delete
# version 2
s3.bucket('bucket-name').object('key').delete
• Batch operations - In version 1, all batch operations were hand-coded utilities. In version 2, many batch
operations are auto-generated batching operations over the API. Version 2 batching interfaces are
very different from version 1.
12
Hello World Tutorial
Hello World Tutorial
This tutorial shows you how to use the AWS SDK for Ruby to create a command-line program that performs
some common Amazon S3 operations.
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 methods
provided by the AWS SDK for Ruby.
require 'aws-sdk'
Creating an Amazon S3 Resource
Create an Aws::S3::Resource object in the appropriate region. The following example creates an Amazon S3
resource object in the us-west-2 region. Note that the region is not important as Amazon S3 resources are
not specific to a region.
s3 = Aws::S3::Resource.new(region: 'us-west-2')
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 name
my-bucket.
my_bucket = s3.bucket('my-bucket')
my_bucket.create
Adding a File to the Bucket
Use the #upload_file method to add a file to the bucket. The following example adds the file named
my_file to the bucket named my-bucket.
name = File.basename 'my_file'
obj = s3.bucket('my-bucket').object(name)
obj.upload_file('my_file')
Listing the Contents of a Bucket
To list the contents of a bucket, use the Aws::S3::Bucket:Objects method. The following example lists up to 50
bucket items for the bucket my-bucket.
my_bucket.objects.limit(50).each do |obj|
puts " #{obj.key} => #{obj.etag}"
end
13
Hello World Tutorial
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
create - creates a
upload - uploads a
list
- (default)
perform on the bucket:
new bucket
file to the bucket
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 required
bucket_name = nil
if ARGV.length > 0
bucket_name = ARGV[0]
else
puts USAGE
exit 1
end
# The operation to perform on the bucket
operation = 'list' # default
operation = ARGV[1] if (ARGV.length > 1)
# The file name to use with 'upload'
file = nil
file = ARGV[2] if (ARGV.length > 2)
# Get an Amazon S3 resource
s3 = Aws::S3::Resource.new(region: 'us-west-2')
# Get the bucket by name
bucket = s3.bucket(bucket_name)
14
Hello World Tutorial
case operation
when 'create'
# Create a bucket if it doesn't already exist
if bucket.exists?
puts "The bucket '%s' already exists!" % bucket_name
else
bucket.create
puts "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 bucket
if 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
end
else
NO_SUCH_BUCKET % bucket_name
end
when 'list'
if bucket.exists?
# Enumerate the bucket contents and object etags
puts "Contents of '%s':" % bucket_name
puts ' Name => GUID'
bucket.objects.limit(50).each do |obj|
puts " #{obj.key} => #{obj.etag}"
end
else
NO_SUCH_BUCKET % bucket_name
end
else
puts "Unknown operation: '%s'!" % operation
puts USAGE
end
15
Hello World Tutorial
Running the Program
To list the contents of a bucket, use either of the following commands, where bucket-name is the name of
the bucket to list. We don't have to include list because it is the default operation.
ruby hello-s3.rb bucket-name list
ruby hello-s3.rb bucket-name
To create a bucket, use the following command, where bucket-name is the name of the bucket you want to
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 does not
create another copy.
After you create your bucket, you can upload an object to the bucket. The following command adds
your_file.txt to the bucket.
ruby hello-s3.rb bucket-name upload your_file.txt
Next Steps
Now that you've completed your first AWS SDK for Ruby application, here are some suggestions to extend
the 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 update that
bucket item.
16
Programming with the AWS SDK for Ruby
Programming with the AWS SDK for Ruby
This section provides information about developing software with the AWS SDK for Ruby, including how to
use some of the SDK's advanced features.
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 the http_wire_trace
option. This information helps differentiate client changes, service issues, and user errors. 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 says whether
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"
else
puts "Bucket #{ARGV[0]} does not exist"
end
If the bucket exists, the output looks something like the following, where ACCESS_KEY is the value of your
access key. (Returns were added to the HEAD line for readability.)
opening connection to bucket_name.s3-us-west-1.amazonaws.com:443...
opened
starting SSL for bucket_name.s3-us-west-1.amazonaws.com:443...
SSL established
<- "HEAD / HTTP/1.1\r\n
Content-Type: \r\n
Accept-Encoding: \r\n
User-Agent: aws-sdk-ruby2/2.2.7 ruby/2.1.7 x64-mingw32\r\n
X-Amz-Date: 20160121T191751Z\r\n
Host: bucket_name.s3-us-west-1.amazonaws.com\r\n
X-Amz-Content-Sha256: e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855\r
Authorization: AWS4-HMAC-SHA256 Credential=ACCESS_KEY/20160121/us-west-1/s3/aws4_request
SignedHeaders=host;x-amz-content-sha256;x-amz-date,
Signature=2ca8301c5e829700940d3cc3bca2a3e8d79d177f2c046c34a1a285770db6382
Content-Length: 0\r\n
Accept: */*\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"
17
Programming with the AWS SDK for Ruby
-> "x-amz-id-2: N6BzRLx8b68NmF50g1IxLzT+E4uWPuAIRe7Pl4XKl5STT4tfNO7gBsO8qrrAnG4CbVpU0iIRXmk
-> "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-alive
Bucket bucket_name exists
Stubbing Client Responses and Errors
Learn how to stub client responses and client errors in an AWS SDK for Ruby application.
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)
bucket_names = s3.list_buckets.buckets.map(&:name)
# List each bucket by name
bucket_names.each do |name|
puts name
end
Running this code displays the following.
aws-sdk
aws-sdk2
18
Programming with the AWS SDK for Ruby
Note
After you supply any stubbed data, the default values no longer apply for any remaining instance
attributes. This means that in the previous example, the remaining instance attribute,
creation_date, is not now but nil.
The AWS SDK for Ruby validates your stubbed data. If you pass in data of the wrong type, it raises an
ArgumentError exception. For example, if instead of the previous assignment to bucket_data, you used
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 hash
expected params[:buckets][1] to be a hash
Stubbing Client Errors
You can also stub errors that the AWS SDK for Ruby raises for specific methods. The following example
displays 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)
begin
s3.head_bucket({bucket: 'aws-sdk'})
rescue Exception => ex
puts "Caught #{ex.class} error calling 'head_bucket' on 'aws-sdk'"
end
Paging Response Data
Some AWS calls provide paged responses to limit the amount of data returned with each response. A page of
data represents up to 1,000 items.
Paged Responses Are Enumerable
The simplest way to handle paged response data is to use the built-in enumerator in the response object, as
shown in the following example.
s3 = Aws::S3::Client.new
s3.list_objects(bucket:'aws-sdk').each do |response|
19
Programming with the AWS SDK for Ruby
puts response.contents.map(&:key)
end
This yields one response object per API call made, and enumerates objects in the named bucket. The SDK
retrieves additional pages of data to complete the request.
Handling Paged Responses Manually
To handle paging yourself, use the response's next_page? method to verify there are more pages to
retrieve, 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 of results,
as shown in the following example.
s3 = Aws::S3::Client.new
# Get the first page of data
response = s3.list_objects(bucket:'aws-sdk')
# Get additional pages
while response.next_page? do
response = 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 an
Aws::PageableResponse::LastPageError exception.
Paged Data Classes
Paged data in the AWS SDK for Ruby is handled by the Aws::PageableResponse class, which is included with
Seahorse::Client::Response to provide access to paged data.
Using Waiters
Waiters are utility methods that poll for a particular state to occur on a client. Waiters can fail after a number of
attempts at a polling interval defined for the service client. For an example of how a waiter is used, see
Creating a Simple Table with a Single Primary Key.
Invoking a Waiter
To invoke a waiter, call #wait_until on a service client. In the following example, a waiter waits until the
instance i-12345678 is running before continuing.
20
Programming with the AWS SDK for Ruby
ec2 = Aws::EC2::Client.new
begin
ec2.wait_until(:instance_running, instance_ids:['i-12345678'])
puts "instance running"
rescue Aws::Waiters::Errors::WaiterFailed => error
puts "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 operation is
being waited for. The second parameter is a hash of parameters that are passed to the client method called
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.
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 client being used.
Aws::Waiters::Errors::TooManyAttemptsError
The number of attempts exceeded the waiter's max_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 occurred while waiting.
All of these errors—except NoSuchWaiterError—are based on WaiterFailed. To catch errors in a
waiter, use WaiterFailed, as shown in the following example.
rescue Aws::Waiters::Errors::WaiterFailed => error
puts "failed waiting for instance running: #{error.message}"
end
Configuring a Waiter
Each waiter has a default polling interval and a maximum number of attempts it will make before returning
control 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 seconds
client.wait_until(...) do |w|
w.max_attempts = 5
21
Programming with the AWS SDK for Ruby
w.delay = 5
end
To disable wait failures, set the value of either of these parameters to nil.
Extending a Waiter
To modify the behavior of waiters, you can register callbacks that are triggered before each polling attempt
and before waiting.
The following example implements an exponential backoff in a waiter by doubling the amount of time to wait
on every attempt.
ec2 = Aws::EC2::Client.new
ec2.wait_until(:instance_running, instance_ids:['i-12345678']) do |w|
w.interval = 0 # disable normal sleep
w.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 (3600
seconds) before failing.
started_at = Time.now
client.wait_until(...) do |w|
# Disable max attempts
w.max_attempts = nil
# Poll for 1 hour, instead of a number of attempts
before_wait do |attempts, response|
throw :failure if Time.now - started_at > 3600
end
end
Specifying a Client Timeout Duration
The following example creates an Amazon S3 client in the region us-west-2, and specifies to wait 5 seconds
between two retries on every client operation. By default, the SDK performs up to three retries, with 15
seconds between retries, for a total of up to four attempts. Therefore, an operation could take 60 seconds 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)
22
AWS SDK for Ruby Code Examples
AWS SDK for Ruby Code Examples
This section provides examples you can use to access AWS services by using the AWS SDK for Ruby.
Amazon CloudWatch Examples
You can use the following examples to access Amazon CloudWatch (CloudWatch) by using the AWS SDK for
Ruby. For more information about CloudWatch, see the CloudWatch Developer Guide.
Examples
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 Name2
resp = client.describe_alarms
resp.metric_alarms.each
puts 'Name:
puts 'State:
puts ' reason:
puts 'Metric:
puts 'Namespace:
puts 'Statistic:
puts 'Dimensions (' +
do |alarm|
' + alarm.alarm_name
' + alarm.state_value
' + alarm.state_reason
' + alarm.metric_name
' + alarm.namespace
' + alarm.statistic
alarm.dimensions.length.to_s + '):'
alarm.dimensions.each do |d|
puts ' Name:
' + d.name
puts ' Value:
' + d.value
end
puts
puts
puts
puts
puts
puts
end
'Period:
'Unit:
'Eval periods:
'Threshold:
'Comp operator:
'
'
'
'
'
+
+
+
+
+
alarm.period.to_s
alarm.unit.to_s
alarm.evaluation_periods.to_s
alarm.threshold.to_s
alarm.comparison_operator
Creating an Alarm
The following example creates a CloudWatch alarm my-alarm that sends a message through the Amazon
SNS topic with the ARN ARN when the Amazon S3 bucket my-bucket has more than 50 items in a 24-hour
period.
23
AWS SDK for Ruby Code Examples
require 'aws-sdk'
# Placeholder for put_metric_alarm args
args = {}
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 << dim1
dimensions << dim2
args[:dimensions] = dimensions
args[:statistic] = 'Maximum'
# NumberOfObjects REQUIRES this value
args[:period] = 86400
# NumberOfObjects REQUIRES this value
args[:unit] = nil
args[:evaluation_periods] = 1
args[:threshold] = 50
args[:comparison_operator] = 'GreaterThanThreshold'
cw = Aws::CloudWatch::Client.new(region: 'us-west-2')
cw.put_metric_alarm(args)
Enabling and Disabling Alarm Actions
An Amazon CloudWatch alarm watches a single metric over a time period you specify. The CloudWatch alarm
performs one or more actions based on the value of the metric, relative to a given threshold over a number 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.
24
AWS SDK for Ruby Code Examples
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 described in:
• 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 a valid 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 speci
actions_enabled: true, # Run actions if the alarm's state changes.
metric_name: "NumberOfObjects",
alarm_actions: [ "arn:aws:sns:REGION-ID:ACCOUNT-ID:TOPIC-NAME" ], # Notify this Amazon SNS topic
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.
25
AWS SDK for Ruby Code Examples
})
# Disable all actions for the alarm.
cw.disable_alarm_actions({
alarm_names: [ alarm_name ]
})
Getting Info about Custom Metrics
A CloudWatch alarm watches a single metric over a time period you specify. The CloudWatch alarm performs
one or more actions based on the value of the metric, relative to a given threshold over a number 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. 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 described in:
• Installing the AWS SDK for Ruby
• Configuring the AWS SDK for Ruby
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"
}
26
AWS SDK for Ruby Code Examples
],
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"
}
]
})
# Get information about custom metrics.
list_metrics_output = cw.list_metrics({
namespace: "SITE/TRAFFIC"
})
list_metrics_output.metrics.each do |metric|
puts metric.metric_name
metric.dimensions.each do |dimension|
puts "#{dimension.name} = #{dimension.value}"
end
puts "\n"
end
Sending Events to Amazon CloudWatch Events
CloudWatch Events delivers a near real-time stream of system events that describe changes in AWS
resources to AWS Lambda functions or other targets. To learn more, see What is Amazon CloudWatch
Events?. 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.
27
AWS SDK for Ruby Code Examples
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
using
Aws::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 described in:
• 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 function ARN.
1. Create a Lambda function, as described here.
2. Name the function LogEC2InstanceStateChange.
3. For a role, select Choose
lambda_basic_execution.
an
Existing
Role.
For
the
existing
role,
select
4. After you create the function, copy the ARN and paste it into your code.
• Replace the placeholder value assigned to cwe_service_role_arn with an appropriate AWS IAM service
role ARN.
1. In the IAM console, create a role and attach a policy that grants full access to CloudWatch Events.
2. Ensure that the role has a trust relationship to events.amazonaws.com. For an example policy and
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 role ARN
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:LogEC2InstanceStateChan
# 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"
28
AWS SDK for Ruby Code Examples
# 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,
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 ])
29
AWS SDK for Ruby Code Examples
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,
},
],
start_time: Time.now - 600, # Look back over the past 10 minutes to see if the rule was triggered (10 minutes *
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 be
statistics: [ "Sum" ],
unit: "Count"
})
if invocations.datapoints.count > 0
puts "Rule invocations:"
invocations.datapoints.each do |datapoint|
puts " #{datapoint.sum} invocation(s) at #{datapoint.timestamp}"
end
else
puts "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 lates
})
30
AWS SDK for Ruby Code Examples
puts "\nLog messages:\n\n"
get_log_events_response.events.each do |event|
puts event.message
end
Amazon DynamoDB Examples
You can use the following examples to access Amazon DynamoDB services by using the AWS SDK for Ruby.
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.
The topic also provides a link to a downloadable version of DynamoDB, which includes an interactive web
interface so you can experiment with DynamoDB offline.
Examples
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
Creating a Simple Table with a Single Primary Key
The following example creates the table Users with three attributes: ID, FirstName, and LastName in the
us-west-2 region.
The wait_until call blocks you from using the table until DynamoDB has created it. By default, the
DynamoDB client's wait_until method checks every 20 seconds, up to a maximum of 500 seconds, to see
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' }
31
AWS SDK for Ruby Code Examples
]
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:
key_schema:
projection:
provisioned_throughput:
}]
'LastNameFirstNameIndex',
index_schema,
{ projection_type: 'ALL' },
{ read_capacity_units: 5, write_capacity_units: 10 }
request = {
attribute_definitions:
table_name:
key_schema:
global_secondary_indexes:
provisioned_throughput:
}
attribute_defs,
'Users',
key_schema,
global_indexes,
{ 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')
Adding an Item to a Table
The following example adds an item with the ID value of 123456, FirstName value of John, and LastName
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'
}})
32
AWS SDK for Ruby Code Examples
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
keys.each do |k|
puts "#{k}: #{item[k]}"
end
end
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 table in
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}"
Updating a Table
The following example updates all the items in the Users table in the us-west-2 region to include a new
field, airmiles, and sets the value to 10000.
33
AWS SDK for Ruby Code Examples
require 'aws-sdk'
dynamoDB = Aws::DynamoDB::Resource.new(region: 'us-west-2')
table = dynamoDB.table('Users')
# Get the IDs of all of the users
resp = 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' }
}
# Update the item in the table:
table.update_item(request)
end
Creating an Index
The following example adds a new index, air-mileage-index, to the Users table in the us-west-2
region. Once the status of the index is ACTIVE, you can search for items in the table based on 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: {
34
AWS SDK for Ruby Code Examples
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)
Amazon EC2 Examples
You can use the following examples to access Amazon Elastic Compute Cloud (Amazon EC2) using the AWS
SDK for Ruby. For more information about Amazon EC2, see the Amazon EC2 Documentation.
Examples
Creating a VPC
The following example creates the virtual private cloud (VPC) MyGroovyVPC with the CIDR block
10.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 DNS
vpc.modify_attribute({
enable_dns_support: { value: true }
})
vpc.modify_attribute({
enable_dns_hostnames: { value: true }
})
# Name our VPC
vpc.create_tags({ tags: [{ key: 'Name', value: 'MyGroovyVPC' }]})
puts vpc.vpc_id
Creating an Internet Gateway and Attaching It to a VPC
35
AWS SDK for Ruby Code Examples
The following example creates an Internet gateway MyGroovyIGW, attaches it to a VPC that has ID VPC_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
Creating a Public Subnet
The following example creates a public subnet MyGroovySubnet in the us-west-2 region and the
Availablity Zone us-west-2a. The example attaches the public subnet to a VPC with the ID VPC_ID that
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
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 VPC with the
ID VPC_ID. The route table uses the route with the CIDR block 0.0.0.0/0 and the gateway with the ID
IGW_ID. The example associates the route table with the subnet that has ID SUBNET_ID, and then 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
})
36
AWS SDK for Ruby Code Examples
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
Using Elastic IP Addresses in Amazon EC2
An Elastic IP address is a static IP address, designed for dynamic cloud computing, that is associated with
your AWS account. It's a public IP address, which is reachable from the Internet. If your instance doesn't have
a public IP address, you can use an Elastic IP address with your instance so that it can communicate with the
Internet.
For more information about Elastic IP addresses in Amazon EC2, see Elastic IP Addresses in the Amazon EC2
User Guide for Linux Instances or Elastic IP Addresses in the Amazon EC2 User Guide for Windows Instances.
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 the Aws::EC2::Client#associate_address
method.
3. Get
information
about
addresses
associated
Aws::EC2::Client#describe_addresses method.
with
the
instance
by
using
the
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, as
described 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.
37
AWS SDK for Ruby Code Examples
Note
Before you run the following code, you must replace the INSTANCE-ID string with your actual instance
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: [
{
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 "=" * 10
puts "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}"
end
end
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 t
display_addresses(ec2, instance_id)
38
AWS SDK for Ruby Code Examples
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 fr
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)
Creating a Security Group
The following example creates a security group MyGroovySecurityGroup in the us-west-2 region on 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 for MyGroovyInstance".
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
Working with Security Groups in Amazon EC2
39
AWS SDK for Ruby Code Examples
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 the rules
for a security group at any time; the new rules are automatically applied to all instances that are associated
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.
Prerequisites
Before working with the code below, you need to install and configure the AWS SDK for Ruby. See the
following:
• 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 security
group we're going to create. We also need to provide the ID of our VPC, which is available in the console after
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 group was
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).
40
AWS SDK for Ruby Code Examples
# 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,
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 = true
rescue 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 IP
permissions.
def describe_ip_permission(ip_permission)
puts "-" * 22
41
AWS SDK for Ruby Code Examples
puts "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
end
if 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
end
if ip_permission.prefix_list_ids.count > 0
puts "Prefix List IDs:"
ip_permission.prefix_list_ids.each do |prefix_list_id|
puts " #{prefix_list_id.prefix_list_id}"
end
end
if 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 " ." * 7
puts " 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
end
end
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 "=" * 22
puts "IP Permissions:"
security_group.ip_permissions.each do |ip_permission|
describe_ip_permission(ip_permission)
42
AWS SDK for Ruby Code Examples
end
end
if security_group.ip_permissions_egress.count > 0
puts "=" * 22
puts "IP Permissions Egress:"
security_group.ip_permissions_egress.each do |ip_permission|
describe_ip_permission(ip_permission)
end
end
if security_group.tags.count > 0
puts "=" * 22
puts "Tags:"
security_group.tags.each do |tag|
puts " #{tag.key} = #{tag.value}"
end
end
end
Delete a Security Group
At the end of the script, assuming that a security group was successfully created and the
security_group_created flag set to true, we delete the security group.
if security_group_created
ec2.delete_security_group({ group_id: create_security_group_result.group_id })
end
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 for Linux
Instances or Amazon EC2 Key Pairs and Windows Instances in the Amazon EC2 User Guide for Windows
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:
43
AWS SDK for Ruby Code Examples
• 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 the
create_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.
• key_material, which gets the unencrypted PEM encoded RSA private key.
puts
puts
puts
puts
puts
"Created key pair '#{key_pair.key_name}'."
"\nSHA-1 digest of the DER encoded private key:"
"#{key_pair.key_fingerprint}"
"\nUnencrypted PEM encoded RSA private key:"
"#{key_pair.key_material}"
In this code, key_pair is a variable representing an Aws::EC2::KeyPair object, which is returned by calling
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 > 0
puts "\nKey pair names:"
key_pairs_result.key_pairs.each do |key_pair|
puts key_pair.key_name
end
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::DescribeKeyPairsResult object that
is returned by calling the describe_key_pairs method.
• Calling the Aws::EC2::Types::DescribeKeyPairsResult object's key_pairs method returns 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.
44
AWS SDK for Ruby Code Examples
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.
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::InvalidKeyPairDuplicate
puts "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 > 0
puts "\nKey pair names:"
key_pairs_result.key_pairs.each do |key_pair|
puts key_pair.key_name
end
end
# Delete the key pair.
ec2.delete_key_pair({
key_name: key_pair_name
})
45
AWS SDK for Ruby Code Examples
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 AWS
services 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 to the AWS
actions and resources described in this example. This example assumes you have set the credentials in
the AWS credentials profile file or in the AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY
environment variables on your local system.
Getting Information about All Instances
The following example lists the IDs and states (pending, running, shutting down, terminated, stopping, or
stopped) for all of your Amazon EC2 instances in the us-west-2 region.
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
Getting Information about All Instances with a Specific Tag Value
The following example lists the ID and state (pending, running, shutting down, terminated, stopping, or
stopped) of an Amazon EC2 instance with the tag Group and tag value MyGroovyGroup in the us-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.id
puts 'State: ' + i.state.name
end
46
AWS SDK for Ruby Code Examples
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
Creating an Instance
The following example creates an Amazon EC2 instance MyGroovyInstance, with the tag Group and value
MyGroovyGroup. The instance is created in Availability Zone us-west-2a with the machine image
MACHINE_IMAGE for the account with ID ACCOUNT_ID, the security group with the ID SECURITY_GROUP_ID,
and the subnet with the ID SUBNET_ID. Then, it displays the instance's public DNS and IP address.
Note
In the empty script value, you can add instructions that your Amazon EC2 instance executes when it
starts.
require 'aws-sdk'
require 'base64'
# User code that's executed when the instance starts
script = ''
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'
47
AWS SDK for Ruby Code Examples
},
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 checks
ec2.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', v
puts instance.id
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.code
when 48 # terminated
puts "#{id} is terminated, so you cannot stop it"
when 64 # stopping
puts "#{id} is stopping, so it will be stopped in a bit"
when 89 # stopped
puts "#{id} is already stopped"
else
i.stop
end
end
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')
48
AWS SDK for Ruby Code Examples
i = ec2.instance('i-123abc')
if i.exists?
case i.state.code
when 0 # pending
puts "#{id} is pending, so it will be running in a bit"
when 16 # started
puts "#{id} is already started"
when 48 # terminated
puts "#{id} is terminated, so you cannot start it"
else
i.start
end
end
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.code
when 48 # terminated
puts "#{id} is terminated, so you cannot reboot it"
else
i.reboot
end
end
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 described in:
49
AWS SDK for Ruby Code Examples
• 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!
def wait_for_instances(ec2, state, ids)
begin
ec2.wait_until(state, instance_ids: ids)
puts "Success: #{state}."
rescue Aws::Waiters::Errors::WaiterFailed => error
puts "Failed: #{error.message}"
end
end
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}'..."
begin
monitor_instances_result = ec2.monitor_instances({
instance_ids: [instance_id]
})
puts "Detailed monitoring state for instance '#{instance_id}': #{monitor_instances_result.
rescue Aws::EC2::Errors::InvalidState
puts "Instance '#{instance_id}' is not in a monitorable state. Continuing on..."
end
# Get information about available instances.
50
AWS SDK for Ruby Code Examples
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}"
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
end
end
end
end
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.code
when 48 # terminated
puts "#{id} is already terminated"
else
i.terminate
51
AWS SDK for Ruby Code Examples
end
end
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.
For more information about Amazon EC2 regions and Availability Zones, see Regions and Availability Zones
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, see Complete
Example.
1. Get an Aws::EC2::Types::DescribeRegionsResult object, which is returned by the describe_regions
method and represented in this code by the describe_regions_result variable.
2. Use the DescribeRegionsResult object's regions
Aws::EC2::Types::Region objects representing the regions.
attribute
to
get
an
array
of
3. Get each region's name and endpoint by using the Region object's region_name and endpoint
attributes.
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
of
Aws::EC2::Types::AvailabilityZone
objects
representing
the
Availability
Zones.
The
DescribeAvailabilityZonesResult object is returned by the describe_availability_zones
method and represented in this code by the describe_availability_zones_result variable.
In this code, ec2 is a variable representing an Aws::EC2::Client object. For more information, see Complete
Example.
Use the AvailabilityZone object's zone_name and state attributes.
52
AWS SDK for Ruby Code Examples
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
end
end
1. Use
the
AvailabilityZone
object's
Aws::EC2::Types::AvailabilityZoneMessage array.
messages
attribute,
which
returns
an
2. If there is at least one message in the array, use each AvailabilityZoneMessage object's message
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
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}"
end
end
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 AWS
services 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 to the AWS
actions and resources described in this example. This example assumes you have set the credentials in
the AWS credentials profile file or in the AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY
environment variables on your local system.
53
AWS SDK for Ruby Code Examples
AWS Elastic Beanstalk Examples
You can use the following examples to access AWS Elastic Beanstalk (Elastic Beanstalk) using the AWS SDK
for Ruby. For more information about Elastic Beanstalk, see the Elastic Beanstalk Developer Guide.
Examples
Getting Information about All Applications
The following example lists the names, descriptions, and URLs of all of your Elastic Beanstalk applications 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 |e
puts " Environment: #{env.environment_name}"
puts "
URL:
#{env.cname}"
puts "
Health:
#{env.health}"
end
end
Getting Information about a Specific Application
The following example lists the name, description, and URL of the MyRailsApp application in the us-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:
puts "Description:
#{app.application_name}"
#{app.description}"
envs = elb.describe_environments({application_name: app.application_name})
puts "URL:
#{envs.environments[0].cname}"
end
Updating a Ruby on Rails Application
The following example updates the Ruby on Rails application MyRailsApp in the us-west-2 region.
54
AWS SDK for Ruby Code Examples
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.new
s3 = Aws::S3::Client.new
app_name = 'MyRailsApp'
# Get S3 bucket containing app
app_versions = elb.describe_application_versions({ application_name: app_name })
av = app_versions.application_versions[0]
bucket = av.source_bundle.s3_bucket
s3_key = av.source_bundle.s3_key
# Get info on environment
envs = elb.describe_environments({ application_name: app_name })
env = envs.environments[0]
env_name = env.environment_name
# Create new storage location
resp = elb.create_storage_location()
puts "Created storage location in bucket #{resp.s3_bucket}"
resp = s3.list_objects({
prefix: s3_key,
bucket: bucket
})
# Create ZIP file
zip_file_basename = SecureRandom.urlsafe_base64.to_s
zip_file_name = zip_file_basename + '.zip'
# Call out to OS to produce ZIP file
cmd = "git archive --format=zip -o #{zip_file_name} HEAD"
%x[ #{cmd} ]
# Get ZIP file contents
zip_contents = File.read(zip_file_name)
key = app_name + "\\" + zip_file_name
55
AWS SDK for Ruby Code Examples
resp = s3.put_object({
body: zip_contents,
bucket: bucket,
key: key
})
date = Time.new
today = 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
})
AWS Identity and Access Management Examples
You can use the following examples to access AWS Identity and Access Management (IAM) using the AWS
SDK for Ruby. For more information about IAM, see the IAM documentation.
Examples
Getting Information about All Users
The following example lists the groups, policies, and access key IDs of all IAM users in the us-west-2
region.
require 'aws-sdk'
iam = Aws::IAM::Client.new(region: 'us-west-2')
iam.list_users.users.each do |user|
name = user.user_name
puts "For user #{name}"
puts " In groups:"
iam.list_groups_for_user({user_name: name}).groups.each do |group|
puts "
#{group.group_name}"
end
56
AWS SDK for Ruby Code Examples
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}"
end
end
Adding a New User
The following example creates the IAM |user my_groovy_user in the us-west-2 region with the password
REPLACE_ME, and displays the user's account ID. If a user with that name already exists, it displays a
message and does not create a new user.
require 'aws-sdk'
iam = Aws::IAM::Client.new(region: 'us-west-2')
begin
user = 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::EntityAlreadyExists
puts 'User already exists'
end
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')
begin
user = iam.user(user_name: 'my_groovy_user')
key_pair = user.create_access_key_pair
57
AWS SDK for Ruby Code Examples
puts "Access key: #{key_pair.access_key_id}"
puts "Secret key: #{key_pair.secret}"
rescue Aws::IAM::Errors::NoSuchEntity => ex
puts 'User does not exist'
end
Adding a Managed Policy
The following example adds the managed policy AmazonS3FullAccess to the IAM user my_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 exist
begin
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
Creating a Role
The following example creates the role my_groovy_role so that Amazon EC2 can access Amazon S3 and
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 role
policy_doc = {
Version:"2012-10-17",
Statement:[
{
Effect:"Allow",
Principal:{
Service:"ec2.amazonaws.com"
},
Action:"sts:AssumeRole"
}]
}
58
AWS SDK for Ruby Code Examples
role = iam.create_role({
role_name: 'my_groovy_role',
assume_role_policy_document: policy_doc.to_json
})
# Give the role full access to S3
role.attach_policy({
policy_arn: 'arn:aws:iam::aws:policy/AmazonS3FullAccess'
})
# Give the role full access to DynamoDB
role.attach_policy({
policy_arn: 'arn:aws:iam::aws:policy/AmazonDynamoDBFullAccess'
})
Managing IAM Users
An IAM user represents a person or service that interacts with AWS. For more information about IAM users,
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 described in:
• 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.
def list_user_names(iam)
list_users_response = iam.list_users
list_users_response.users.each do |user|
puts user.user_name
59
AWS SDK for Ruby Code Examples
end
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..."
begin
iam.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::EntityAlreadyExists
puts "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)
Working with IAM Policies
An IAM policy is a document that specifies one or more permissions. For more information about IAM policies,
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.
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.
60
AWS SDK for Ruby Code Examples
Prerequisites
Before running the example code, you need to install and configure the AWS SDK for Ruby, as described in:
• 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..."
iam.attach_role_policy({
role_name: role_name,
policy_arn: policy_arn
})
61
AWS SDK for Ruby Code Examples
# List policies attached to the role.
puts "\nAttached role policy ARNs..."
iam.list_attached_role_policies({ role_name: role_name }).attached_policies.each do |attach
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
})
Managing IAM Access Keys
Users need their own access keys to make programmatic calls to AWS from the SDK for Ruby. To fill this
need, you can create, modify, view, or rotate access keys (access key IDs and secret access keys) for IAM
users. By default, when you create an access key, its status is Active, which means the user can use the
access key for API calls. For more information about access keys, see Managing Access Keys for IAM Users.
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 described in:
• 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 the
IAM console or programmatically, as shown at Adding a New User.
Example
require 'aws-sdk'
iam = Aws::IAM::Client.new(region: 'us-east-1')
user_name = "my-user"
# List user access keys.
62
AWS SDK for Ruby Code Examples
def list_keys(iam, user_name)
begin
list_access_keys_response = iam.list_access_keys({ user_name: user_name })
if list_access_keys_response.access_key_metadata.count == 0
puts "No access keys."
else
puts "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::NoSuchEntity
puts "Cannot find user '#{user_name}'."
exit(false)
end
end
puts "Before creating access key..."
list_keys(iam, user_name)
# Create an access key.
puts "\nCreating access key..."
begin
iam.create_access_key({ user_name: user_name })
puts "\nAfter creating access key..."
list_keys(iam, user_name)
rescue Aws::IAM::Errors::LimitExceeded
puts "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_
# 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"
63
AWS SDK for Ruby Code Examples
})
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)
Working with IAM Server Certificates
To enable HTTPS connections to your website or application on AWS, you need an SSL/TLS server
certificate. To use a certificate that you obtained from an external provider with your website or application on
AWS, you must upload the certificate to IAM or import it into AWS Certificate Manager. For more information
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, using Aws::IAM::Client#list_server_certificates.
Prerequisites
Before running the example code, you need to install and configure the AWS SDK for Ruby, as described in:
• Installing the AWS SDK for Ruby
• Configuring the AWS SDK for Ruby
Note also that the server certificate
Aws::IAM::Errors::NoSuchEntity error.
must
already
exist,
or
the
script
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.
64
will
throw
an
AWS SDK for Ruby Code Examples
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 == 0
puts "No server certificates."
else
list_server_certificates_response.server_certificate_metadata_list.each do |certificate_m
puts "-" * certificate_metadata.server_certificate_name.length
puts "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_metad
end
end
Managing IAM Account Aliases
If you want the URL for your sign-in page to contain your company name or other friendly identifier instead of
your AWS account ID, you can create an alias for your AWS account ID. If you create an AWS account alias,
your sign-in page URL changes to incorporate the alias. For more information about IAM account aliases, see
Your AWS Account ID and Its Alias.
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 described in:
• 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 all Amazon
Web Services products.
Example
65
AWS SDK for Ruby Code Examples
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 == 0
puts "No account aliases."
else
puts "Aliases:"
list_account_aliases_response.account_aliases.each do |account_alias|
puts account_alias
end
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)
# Delete the account alias.
puts "\nDeleting account alias..."
iam.delete_account_alias({ account_alias: account_alias })
puts "\nAfter deleting account alias..."
list_aliases(iam)
Lambda Examples
You can use the following examples to access AWS Lambda (Lambda) using the AWS SDK for Ruby. For
more information about Lambda, see the Lambda documentation.
Examples
Displaying Information about All Lambda Functions
The following example displays the name, ARN, and role of all of your Lambda functions in the us-west-2
region.
66
AWS SDK for Ruby Code Examples
require 'aws-sdk'
client = Aws::Lambda::Client.new(region: 'us-west-2')
client.list_functions.each do |function|
puts 'Name: ' + function.function_name
puts 'ARN: ' + function.function_arn
puts 'Role: ' + function.role
Creating a Lambda Function
The following example creates the Lambda function my-notification-function in the us-west-2
region using these values:
• Role ARN: my-resource-arn. In most cases, you need to attach only the AWSLambdaExecute
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
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.7
args[: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)
Configuring a Lambda Function to Receive Notifications
The following example configures the Lambda function my-notification-function in the us-west-2
region to accept notifications from the resource with the ARN my-resource-arn.
67
AWS SDK for Ruby Code Examples
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]
Amazon Relational Database Service Examples
You can use the following examples to access Amazon Relational Database Service (Amazon RDS) using the
AWS SDK for Ruby. For more information about Amazon RDS, see the Amazon Relational Datbase Service
User Guide.
Note
Some of the following examples use methods that were introduced in the 2.2.18 version of the
Aws::RDS::Resource class. To run those examples, you must use that version or a later version of
the aws-sdk gem.
Examples
Getting Information about All Instances
The following example lists the name (ID) and status of all of your Amazon RDS instances in the us-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
Getting Information about All Snapshots
The following example lists the names (IDs) and status of all of your Amazon RDS (instance) snapshots in the
us-west-2 region.
68
AWS SDK for Ruby Code Examples
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
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}"
puts " Status:
#{s.status}"
end
end
Getting Information about All Security Groups
The following example lists the names of all of your Amazon RDS security groups in the us-west-2 region.
Note
Amazon RDS security groups are only applicable when you are using the Amazon EC2 classic
platform. 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 descriptions
puts 'Security Groups:'
69
AWS SDK for Ruby Code Examples
i.db_security_groups.each do |sg|
puts sg.db_security_group_name
puts ' ' + sg.db_security_group_description
puts
end
# Show any VPC security group IDs and their status
puts 'VPC Security Groups:'
i.vpc_security_groups.each do |vsg|
puts vsg.vpc_security_group_id
puts ' ' + vsg.status
puts
end
end
Getting Information about All Subnet Groups
The following example lists the name and status of all of your Amazon RDS subnet groups in the us-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
puts ' ' + s.subnet_group_status
end
Getting Information about All Parameter Groups
The following example lists the names and descriptions of all of your Amazon RDS parameter groups in the
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_name
puts ' ' + p.description
end
Creating a Snapshot of an Instance
The following example creates a snapshot for the Amazon RDS instance represented by instance_name in the
us-west-2 region.
70
AWS SDK for Ruby Code Examples
Note
If your instance is a member of a cluster, you can't create a snapshot of the instance, but instead must
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.new
date_time = date.year.to_s +
'-' +
date.month.to_s +
'-' +
date.day.to_s +
'-' +
dat
'-' +
dat
id = instance_name + '-' + date_time
instance.create_snapshot({db_snapshot_identifier: id})
puts "Created snapshot #{id}"
Creating a Snapshot of a Cluster
The following example creates a snapshot for the Amazon RDS cluster represented by cluster_name in the
us-west-2 region.
require 'aws-sdk'
rds = Aws::RDS::Resource.new(region: 'us-west-2')
cluster = rds.db_cluster(cluster_name)
date = Time.new
date_time = date.year.to_s +
'-' +
date.month.to_s +
'-' +
date.day.to_s +
id = cluster_name + '-' + date_time
cluster.create_snapshot({db_cluster_snapshot_identifier: id})
puts "Created cluster snapshot #{id}"
Amazon S3 Examples
You can use the following examples to access Amazon Simple Storage Service (Amazon S3) using the AWS
SDK for Ruby. For more information about Amazon S3, see the Amazon S3 documentation.
Examples
71
AWS SDK for Ruby Code Examples
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 it as
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 Getting Information
about All Buckets in a Region to learn how to filter this list to get the buckets only in a specific region.
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't specify 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 == region
puts "#{b.name}"
end
end
Note
If a bucket is not in the region in which you instantiated your Resource object, the SDK emits a
warning message when you call get_bucket_location. You can suppress this message by
redirecting STDERR.
72
AWS SDK for Ruby Code Examples
On Windows, append 2> nul to the command.
On Linux or iOS, append 2> /dev/null to the command.
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 AWS
services 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 to
the 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 file
david.
Configure the SDK
For this example, add require statements so that you can use the classes and methods provided by the
AWS SDK for Ruby for Amazon S3 and work with JSON-formatted data. Then create an Aws::S3::Client
object in the AWS Region where you want to create the bucket and the specified AWS profile. This code
creates the Aws::S3::Client object in the us-east-1 region. Additional variables are also declared for
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
73
AWS SDK for Ruby Code Examples
# Configure SDK
s3 = 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 class to access
the buckets' properties, such as name for each bucket's name.
resp = s3.list_buckets
resp.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)
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 string
representing the file's data.
To confirm whether the file was uploaded successfully, call the list_objects_v2 method. This returns an
instance of the Aws::S3::Types::ListObjectsV2Output class, which represents the bucket's objects. Then use
the contents method of the ListObjectsV2Output class to access the objects' properties, such as key
for each object's name.
s3.put_object(bucket: bucket, key: "file1", body: "My first s3 object")
# Check the file exists
resp = s3.list_objects_v2(bucket: bucket)
resp.contents.each do |obj|
puts obj.key
end
Copy Files between Buckets
74
AWS SDK for Ruby Code Examples
Call the copy_object method, specifying the name of the target bucket to receive the object (bucket), the
names of the source bucket and object to copy over (copy_source), and the name of the new object that is
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 is the
bucket named david-cloud. After the copy operation, test_file in the david-cloud bucket is renamed
file2 in the doc-sample-bucket bucket, and test_file1 in the david-cloud bucket 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::Delete
type 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 by key)
should not be displayed.
s3.delete_objects(
bucket: 'doc-sample-bucket',
delete: {
objects: [
{
key: 'file2'
},
{
key: 'file3'
}
]
}
)
# Verify objects now have been deleted
resp = s3.list_objects_v2(bucket: bucket)
resp.contents.each do |obj|
puts obj.key
end
Complete Example
Here is the complete code for this example.
75
AWS SDK for Ruby Code Examples
require 'aws-sdk'
require 'json'
profile_name = 'david'
region = "us-east-1"
bucket = 'doc-sample-bucket'
my_bucket = 'david-cloud'
# S3
# Configure SDK
s3 = Aws::S3::Client.new(profile: profile_name, region: region)
# Display a List of Amazon S3 Buckets
resp = s3.list_buckets
resp.buckets.each do |bucket|
puts bucket.name
end
# Create a S3 bucket from S3::client
s3.create_bucket(bucket: bucket)
# Upload a file to s3 bucket, directly putting string data
s3.put_object(bucket: bucket, key: "file1", body: "My first s3 object")
# Check the file exists
resp = s3.list_objects_v2(bucket: bucket)
resp.contents.each do |obj|
puts obj.key
end
# Copy files from bucket to 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 multiple objects in a single HTTP request
s3.delete_objects(
bucket: 'doc-sample-bucket',
delete: {
objects: [
{
key: 'file2'
},
{
key: 'file3'
}
76
AWS SDK for Ruby Code Examples
]
}
)
# Verify objects now have been deleted
resp = 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 example uses 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')
Determining Whether a Bucket Exists
There are two cases in which you would want to determine whether a bucket already exists. You perform
these 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, even
ones to which you do not have access. This test helps prevent you from trying to create a bucket with the
name of an existing bucket, which causes an exception.
• You want to perform an operation, such as add an item to a bucket, only on a bucket to which you have
access.
The following example sets bucket_exists to true if a bucket with the name my-bucket already exists.
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 exists and you
have access to the bucket. Again, the region parameter to Client has no effect on the result.
require 'aws-sdk'
bucket_exists = false
client = Aws::S3::Client.new(region: 'us-west-2')
begin
resp = client.head_bucket({bucket: bucket_name, use_accelerate_endpoint: false})
77
AWS SDK for Ruby Code Examples
bucket_exists = true
rescue
end
Getting Information about Bucket Items
A presigned URL gives you access to the object identified in the URL, if the creator of the presigned URL has
permissions to access that object. You can use a presigned URL to allow a user to click a link and see an
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-bucket in
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 items
bucket.objects.limit(50).each do |item|
puts "Name: #{item.key}"
puts "URL:
#{item.presigned_url(:get)}"
end
Uploading an Item to a Bucket
The following example uploads the item (file) C:file.txt to the bucket my-bucket in the us-west-2 region.
Because C:file.txt is the fully qualified name of the file, the name of the item is set 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 name
name = File.basename(file)
# Create the object to upload
obj = s3.bucket(bucket).object(name)
# Upload it
obj.upload_file(file)
Uploading an Item with Metadata to a Bucket
78
AWS SDK for Ruby Code Examples
The following example uploads the item (file) C:file.txt with the metadata key-value pair answer and 42 to the
bucket my-bucket in the us-west-2 region. Because C:file.txt is the fully qualified 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 name
name = File.basename(file)
# Create the object to upload
obj = s3.bucket(bucket).object(name)
# Metadata to add
metadata = {"answer" => "42"}
# Upload it
obj.upload_file(file, metadata: metadata)
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 the us-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 retrieve
obj = s3.bucket('my-bucket').object('my-item')
# Get the item's content and save it to a file
obj.get(response_target: './my-code/my-item.txt')
Changing the Properties for a Bucket Item
The following example adds public read-only access, sets server-side encryption to AES-256, and sets the
storage class to Reduced Redundancy for the item my-item in the bucket my-bucket in the us-west-2
region.
require 'aws-sdk'
args_list = {}
args_list[:bucket] = 'my-bucket'
args_list[:key]
= 'my-item'
79
AWS SDK for Ruby Code Examples
# Where we are getting the source to copy from
args_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-control
args_list[:acl] = 'public-read'
# The encryption can be any of:
# AES256, aws:kms
args_list[:server_side_encryption] = 'AES256'
# The storage_class can be any of:
# STANDARD, REDUCED_REDUNDANCY, STANDARD_IA
args_list[:storage_class] = 'REDUCED_REDUNDANCY'
client = Aws::S3::Client.new(region: 'us-west-2')
client.copy_object(args_list)
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:
• 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 topic
Programming 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 Service
queue, 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
80
AWS SDK for Ruby Code Examples
Creating an Amazon S3 Bucket Notification
The following example enables the Amazon S3 bucket my-bucket to send a notification to the following when
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 function
lc = {}
lc[:lambda_function_arn] = 'my-function-arn'
lc[:events] = events
lambda_configurations = []
lambda_configurations << lc
notification_configuration[:lambda_function_configurations] = lambda_configurations
# Add queue
qc = {}
qc[:queue_arn] = 'my-topic-arn'
qc[:events] = events
queue_configurations = []
queue_configurations << qc
notification_configuration[:queue_configurations] = queue_configurations
# Add topic
tc = {}
tc[:topic_arn] = 'my-topic-arn'
tc[:events] = events
topic_configurations = []
topic_configurations << tc
notification_configuration[:topic_configurations] = topic_configurations
req[:notification_configuration] = notification_configuration
81
AWS SDK for Ruby Code Examples
req[:use_accelerate_endpoint] = false
s3 = Aws::S3::Client.new(region: 'us-west-2')
s3.put_bucket_notification_configuration(req)
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 to
long-term storage or delete them, you can save a lot of time by creating a template for the lifecycle rules and
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:
Run the following code to produce a JSON representation of that rule. Save the output as default.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|
82
AWS SDK for Ruby Code Examples
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":nu
Now that you have the JSON for a lifecycle rule, you can apply it to any other bucket using the following
example, which takes the rule from default.json and applies it to the bucket other_bucket:
require 'aws-sdk'
require 'json'
class Aws::S3::Types::LifecycleExpiration
def to_map
map = Hash.new
self.members.each { |m| map[m] = self[m] }
map
end
def to_json(*a)
to_map.to_json(*a)
end
end
class Aws::S3::Types::Transition
def to_map
map = Hash.new
self.members.each { |m| map[m] = self[m] }
map
end
def to_json(*a)
to_map.to_json(*a)
end
end
class Aws::S3::Types::LifecycleRule
def to_map
map = Hash.new
self.members.each { |m| map[m] = self[m] }
map
end
def to_json(*a)
to_map.to_json(*a)
end
end
83
AWS SDK for Ruby Code Examples
# Pull in contents as a string
value = File.open('default.json', "rb").read
json_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 =
Best Practice
We recommend that you enable the AbortIncompleteMultipartUpload lifecycle rule on your Amazon S3
buckets.
This rule directs Amazon S3 to abort multipart uploads that don't complete within a specified number of
days after being initiated. When the set time limit is exceeded, Amazon S3 aborts the upload and then
deletes the incomplete upload data.
For more information, see Lifecycle Configuration for a Bucket with Versioning in the Amazon S3 User
Guide.
Creating a Bucket Policy with Ruby
This example demonstrates how to use the AWS SDK for Ruby to:
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 AWS
services 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 to
the AWS actions and resources described in this example.
This example assumes you have set the credentials in the AWS credentials profile file or in the
AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY environment variables on your local system.
Configure the SDK
84
AWS SDK for Ruby Code Examples
To configure the SDK for this example, add a require statement so you can use the classes and methods
provided by the AWS SDK for Ruby for Amazon S3. Then create an Aws::S3::Client object in the AWS Region
where you want to create the bucket. This code creates the Aws::S3::Client object in the us-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 to
represent 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.
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 to a
JSON object. This code uses a variable named policy that contains the policy definition. This policy allows
the specified user to have full control over the example-bucket-name (represented by #{bucket}).
Substitute arn:aws:iam::111122223333:user/Alice with the Amazon Resource 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}"
]
85
AWS SDK for Ruby Code Examples
}
]
}.to_json
For examples of the types of policies you can define, see Bucket Policy Examples in the Amazon S3 Developer
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 you need to write.
To do this, retrieve the current policy by calling the get_bucket_policy method. Next, parse the JSON object
that is returned into a Ruby hash. Then make your incremental changes to the policy. For example, this code
changes the ARN of the IAM entity. After you make your changes, call the put_bucket_policy method
again. Be sure to call the to_json method on the hash to convert it back to a JSON object before applying
the changed policy to the bucket.
policy_string = s3.get_bucket_policy(bucket: bucket).policy.read
policy_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 the
bucket.
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.
86
AWS SDK for Ruby Code Examples
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" => [
"arn:aws:s3:::#{bucket}"
]
}
]
}.to_json
s3.put_bucket_policy(
bucket: bucket,
policy: policy
)
policy_string = s3.get_bucket_policy(bucket: bucket).policy.read
policy_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)
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.
87
AWS SDK for Ruby Code Examples
For more information about CORS support in Amazon S3, see Cross-Origin Resource Sharing (CORS) in the
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 AWS
services 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 to
the AWS actions and resources described in this example.
This example assumes:
• 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 the
AWS SDK for Ruby for Amazon S3. Then create an Aws::S3::Client object in the AWS Region where you want
to create the bucket and the specified AWS profile. This code creates the Aws::S3::Client object in 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 client
s3 = 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 things
such as the HTTP methods that the specified origins are allowed to execute (allowed_methods), the origins
you want customers to be able to access the bucket from (allowed_origins), and the headers in the
88
AWS SDK for Ruby Code Examples
response you want customers to be able to access from their applications (for example, from a JavaScript
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.
allowed_methods = []
ARGV.each do |arg|
case arg.upcase
when "POST"
allowed_methods <<
when "GET"
allowed_methods <<
when "PUT"
allowed_methods <<
when "PATCH"
allowed_methods <<
when "DELETE"
allowed_methods <<
when "HEAD"
allowed_methods <<
else
puts "#{arg} is not
end
end
"POST"
"GET"
"PUT"
"PATCH"
"DELETE"
"HEAD"
a valid HTTP method"
For example, assuming the code file is named doc_sample_code_s3_bucket_cors.rb, and you want to
allow the specified origins to execute only GET and POST methods, here is how the user could run the 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 method returns
an Aws::S3::Types::GetBucketCorsOutput object. This object's cors_rules attribute returns an array of
Aws::S3::Types::CORSRule objects, which represent the bucket's CORS settings.
89
AWS SDK for Ruby Code Examples
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 client
s3 = Aws::S3::Client.new(profile: profile_name, region:region)
# Setting a Bucket CORS Configuration
# Create array of allowed methods parameter based on command line parameters
allowed_methods = []
ARGV.each do |arg|
case arg.upcase
when "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 hash
cors_configuration = {
cors_rules: [
{
allowed_methods: allowed_methods,
allowed_origins: ["*"],
expose_headers: ["ExposeHeader"],
},
90
AWS SDK for Ruby Code Examples
]
}
# Set the new CORS configuration on the selected bucket
s3.put_bucket_cors(
bucket: bucket,
cors_configuration: cors_configuration
)
# Retrieving a Bucket CORS Configuration
resp = 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
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 AWS
services 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 to
the AWS actions and resources described in this example.
This example assumes you have set the credentials in the AWS credentials profile file or in the
AWS_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 the
AWS SDK for Ruby for Amazon S3. Then create an Aws::S3::Client object in the AWS Region where you want
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'
91
AWS SDK for Ruby Code Examples
# Create a S3 client
client = 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 sets the
public-read canned ACL on the bucket, which enables full control for the bucket's owner and read-only
access for everyone else.
client.put_bucket_acl({
acl: "public-read",
bucket: bucket,
})
For more information about canned ACLs, see Canned ACL in Access Control List (ACL) Overview in the
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. This code
declares a variable representing the object.
object_key = "my-key"
# Put an object in the public bucket
client.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 Ruby
Net::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 the
object's owner and read-only access for everyone else. After the call, try to get the object's content again.
92
AWS SDK for Ruby Code Examples
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 method returns an
instance of the Aws::S3::Types::GetBucketAclOutput class. Use the grants attribute of the
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 client
client = Aws::S3::Client.new(region: 'us-west-2')
bucket = 'my-bucket'
# Sets a bucket to public-read
client.put_bucket_acl({
acl: "public-read",
bucket: bucket,
})
object_key = "my-key"
# Put an object in the public bucket
client.put_object({
bucket: bucket,
key: object_key,
body: 'Hello World',
})
# Accessing an object in the bucket with unauthorize request
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"
# However, accessing the object is denied since object Acl is not public-read
object_path = "http://#{bucket}.s3-us-west-2.amazonaws.com/#{object_key}"
resp = Net::HTTP.get(URI(object_path))
93
AWS SDK for Ruby Code Examples
puts "Content of unsigned request to #{object_path}:\n\n#{resp}\n\n"
# Setting the object to public-read
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"
# Setting bucket to private again
client.put_bucket_acl({
bucket: bucket,
acl: 'private',
})
# Get current bucket Acl
resp = 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"
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 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 AWS
services and resources. For more information, see Configuring the AWS SDK for Ruby.
94
AWS SDK for Ruby Code Examples
Be sure the AWS credentials map to an AWS Identity and Access Management (IAM) entity with access to
the AWS actions and resources described in this example.
This example assumes you have set the credentials in the AWS credentials profile file or in the
AWS_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 the
AWS SDK for Ruby for Amazon S3. Then create an Aws::S3::Client object in the AWS Region where you want
to create the bucket and the specified AWS profile. This code creates the Aws::S3::Client object in the
us-east-2 region.
An additional variable is also declared for the bucket used in this example. To help ensure the bucket name is
unique across all AWS accounts, an additional require statement is added, and the SecureRandom
module's uuid method is called to generate a unique identifier. This identifier is inserted into the name of the
bucket to be created later in this sample.
require 'aws-sdk'
# Using Random UUIDs to Avoid Collisions when Testing
require 'securerandom'
bucket = "example-test-bucket-#{SecureRandom.uuid}"
# Setup
s3 = 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 not configured
as a website. To confirm this behavior, call the get_bucket_website method. This returns an error,
because there is no website configuration for the bucket.
begin
s3.get_bucket_website(bucket: bucket)
rescue Aws::S3::Errors::NoSuchWebsiteConfiguration
puts "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 the
object's access permissions set. This example adds two webpages to the bucket.
95
AWS SDK for Ruby Code Examples
s3.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"
)
Set a Bucket Website's Configuration
Call the put_bucket_website method, supplying the name of the bucket and the website configuration. For the
website configuration, use an Aws::S3::Types::WebsiteConfiguration hash, supplying the website's index 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
96
AWS SDK for Ruby Code Examples
Call the bucket method of an Aws::S3::Resource object, supplying the name of the bucket. This returns an
Aws::S3::Bucket object. Then call the Aws::S3::Bucket object's delete method.
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 Testing
require 'securerandom'
bucket = "example-test-bucket-#{SecureRandom.uuid}"
# Setup
s3 = Aws::S3::Client.new(region: "us-west-2")
s3.create_bucket(bucket: bucket)
# When Bucket Has No Website Configuration
begin
s3.get_bucket_website(bucket: bucket)
rescue Aws::S3::Errors::NoSuchWebsiteConfiguration
puts "No bucket website configuration present."
end
# Adding Simple Pages & Website Configuration
s3.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"
}
}
97
AWS SDK for Ruby Code Examples
)
# Accessing as a 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"
# Removing Website Configuration
s3.delete_bucket_website(bucket: bucket)
# Cleanup
b = Aws::S3::Resource.new(region: "us-west-2").bucket(bucket)
b.delete! # Recursively deletes objects as well.
Amazon SNS Examples
You can use the following examples to access Amazon Simple Notification Service (Amazon SNS) using the
AWS SDK for Ruby. For more information about Amazon SNS, see the Amazon SNS documentation.
Examples
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
Creating a Topic
The following example creates the topic MyGroovyTopic in the us-west-2 region and displays the resulting
topic ARN.
require 'aws-sdk'
sns = Aws::SNS::Resource.new(region: 'us-west-2')
topic = sns.create_topic(name: 'MyGroovyTopic')
puts topic.arn
Getting Information about All Subscriptions in a Topic
98
AWS SDK for Ruby Code Examples
The following example lists the email addresses of the SNS subscriptions for the topic with the ARN
arn: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
Creating a Subscription in a Topic
The
following
example
creates
a
subscription
for
the
topic
with
the
ARN
arn:aws:sns:us-west-2:123456789:MyGroovyTopic for a user who has the email address
[email protected] in the us-west-2 region, and displays the resulting ARN. Initially the ARN
value is pending confirmation. When the user confirms their email address, this value becomes a true 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
Sending a Message to All Topic Subscribers
The following example sends the message "Hello!" to all subscribers to the topic with the ARN
arn: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({
message: 'Hello!'
})
Enabling a Resource to Publish to a Topic
99
AWS SDK for Ruby Code Examples
The following example enables the resource with the ARN my-resource-arn to publish to the topic with 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
})
Amazon SQS Examples
You can use the following examples to access Amazon Simple Queue Service (Amazon SQS) using the AWS
SDK for Ruby. For more information about Amazon SQS, see the Amazon SQS documentation.
Examples
Getting Information about All Queues in Amazon SQS
The following example lists the URLs, ARNs, messages available, and messages in flight of your Amazon
SQS queues in the us-west-2 region.
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
100
AWS SDK for Ruby Code Examples
# Get ARN, messages available, and messages in flight for queue
req = 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:
' + arn
puts 'Messages available: ' + msgs_available
puts 'Messages in flight: ' + msgs_in_flight
puts
end
Creating a Queue in Amazon SQS
The following example creates the Amazon SQS queue MyGroovyQueue in the us-west-2 region and
displays 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
Working with Queues in Amazon SQS
Amazon SQS provides highly scalable hosted queues for storing messages as they travel between
applications 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:
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
101
AWS SDK for Ruby Code Examples
Before running the example code, you need to install and configure the AWS SDK for Ruby, as described in:
• 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_url
end
# Create a queue.
queue_name = "my-queue"
begin
sqs.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::QueueDeletedRecently
puts "A queue with the name '#{queue_name}' was recently deleted. Wait at least 60 seconds
exit(false)
end
# Get the queue's URL.
queue_url = sqs.get_queue_url(queue_name: queue_name).queue_url
puts queue_url
# Delete the queue.
sqs.delete_queue(queue_url: queue_url)
Sending Messages in Amazon SQS
The following example sends the message "Hello world" through 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.send_message(queue_url: URL, message_body: 'Hello world')
102
AWS SDK for Ruby Code Examples
The following example sends the messages "Hello world" and "How is the weather?" through 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')
resp = sqs.send_message_batch({
queue_url: URL,
entries: [
{
id: 'msg1',
message_body: 'Hello world'
},
{
id: 'msg2',
message_body: 'How is the weather?'
}
],
})
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 learn more,
see Tutorial: Sending a Message to an Amazon SQS Queue and Tutorial: Receiving and Deleting a Message
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.
Prerequisites
Before running the example code, you need to install and configure the AWS SDK for Ruby, as described in:
• 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.
103
AWS SDK for Ruby Code Examples
queue_name = "my-queue"
begin
queue_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-1
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,
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.body
puts "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,
104
AWS SDK for Ruby Code Examples
receipt_handle: message.receipt_handle
})
end
Receiving Messages in Amazon SQS
The following example displays the body of up to 10 messages in the Amazon SQS queue with the URL URL
in the us-west-2 region.
Note
receive_message does not guarantee to get all messages (see Properties of Distributed Queues),
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
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 Amazon SQS
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')
resp = sqs.receive_message(queue_url: URL, max_number_of_messages: 10, wait_time_seconds: 1
resp.messages.each do |m|
puts m.body
end
Enabling Long Polling in Amazon SQS
Long polling helps lower your cost of using Amazon SQS by reducing the number of empty responses and
eliminating false empty responses. For more information about long polling, see Amazon SQS Long Polling.
105
AWS SDK for Ruby Code Examples
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 described in:
• 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 Amazon SQS
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.
},
})
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::NonExistentQueue
puts "Cannot set long polling for a queue named '#{existing_queue_name}', as it does not e
end
# Set long polling when receiving messages for a queue.
106
AWS SDK for Ruby Code Examples
# 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_na
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({
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}"
end
end
# 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::NonExistentQueue
puts "Cannot receive messages using Aws::SQS::QueuePoller for a queue named '#{receive_qu
end
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 the SQS
queue with the URL URL in the us-west-2 region, and deletes the message. After approximately 15 seconds
of inactivity, the script times out.
107
AWS SDK for Ruby Code Examples
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 duration
seconds.
You can get the correct URL by executing the Amazon SQS example in Getting Information about All Queues
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|
puts msg.body
end
The following example loops through the Amazon SQS queue with the URL URL, and gives you up to the
visibility timeout seconds to process the message, represented by the method do_something.
require 'aws-sdk'
# Process the message
def do_something(msg)
puts msg.body
end
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 the visibility
timeout seconds, for any message that needs additional processing by the method do_something2.
require 'aws-sdk'
108
AWS SDK for Ruby Code Examples
# Process the message
def do_something(msg)
true
end
# Do additional processing
def do_something2(msg)
puts msg.body
end
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 processing
poller.change_message_visibility_timeout(msg, timeout)
do_something2(msg)
end
end
Redirecting Dead Letters in Amazon SQS
The following example redirects any dead letters from the queue with the URL URL to the queue with the ARN
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}\"}"
}
})
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)
109
AWS SDK for Ruby Code Examples
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 queue with
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":{
"AWS:SourceArn":"' + my-resource-arn + '"}
}
}]
}'
sqs.set_queue_attributes({
queue_url: my-queue-url,
attributes: {
Policy: policy
}
})
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 these
messages in the dead letter queue to determine why their processing didn't succeed. For more information
about 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 using Aws::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.
110
AWS SDK for Ruby Code Examples
Prerequisites
Before running the example code, you need to install and configure the AWS SDK for Ruby, as described in:
• 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.
Note: For the sake of simplicity, the example code below does not demonstrate
Aws::SQS::Client#add_permission. In a real-world scenario, you should always restrict access to actions such
as SendMessage, ReceiveMessage, DeleteMessage, and DeleteQueue. Not doing so could cause
information disclosure, denial of service, or injection of messages into your queues.
Example
require 'aws-sdk'
# Uncomment for Windows.
# Aws.use_bundled_cert!
sqs = Aws::SQS::Client.new(region: 'us-east-1')
# 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 d
"deadLetterTargetArn" => dead_letter_queue_arn
}.to_json
sqs.set_queue_attributes({
queue_url: queue_url,
111
AWS SDK for Ruby Code Examples
attributes: {
"RedrivePolicy" => redrive_policy
}
})
rescue Aws::SQS::Errors::NonExistentQueue
puts "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)
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}"
end
end
# 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 > 0
puts "\n#{receive_message_result.messages[0].body}"
else
puts "\nNo messages received."
end
Specifying the Message Visibility Timeout in Amazon SQS
In Amazon SQS, immediately after a message is received, it remains in the queue. To prevent other
consumers from processing the message again, Amazon SQS sets a visibility timeout. This is a period of time
112
AWS SDK for Ruby Code Examples
during which Amazon SQS prevents other consuming components from receiving and processing the
message. 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 using
Aws::SQS::Client#change_message_visibility.
Prerequisites
Before running the example code, you need to install and configure the AWS SDK for Ruby, as described in:
• 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')
begin
queue_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_
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 seco
})
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_
113
AWS SDK for Ruby Code Examples
rescue Aws::SQS::Errors::NonExistentQueue
puts "Cannot receive messages for a queue named '#{receive_queue_name}', as it does not ex
end
114
AWS SDK for Ruby Tips and Tricks
AWS SDK for Ruby Tips and Tricks
This section provides tips and tricks on using the AWS SDK for Ruby with AWS services.
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 Started Guide.
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_address
ec2.associate_address(instance_id:"i-12345678", allocation_id: resp.allocation_id)
115
Document History
Document History
To view the list of changes to the AWS SDK for Ruby and its documentation, see the CHANGELOG.md file in
the aws/aws-sdk-ruby repository in GitHub.
116
About Amazon Web Services
About Amazon Web Services
Amazon Web Services (AWS) is a collection of digital infrastructure services that developers can leverage
when developing their applications. The services include computing, storage, database, and application
synchronization (messaging and queuing). AWS uses a pay-as-you-go service model: you are charged only
for the services that you—or your applications—use. For new AWS users, a free usage tier is available. On
this tier, services are free below a certain level of usage. For more information about AWS costs and the Free
Tier, see Use the AWS Free Tier. To obtain an AWS account, visit the AWS home page and click Create a
Free Account.
117