aws sdk for ruby › sdk-for-ruby › latest › ...aws sdk for ruby to create ruby applications...

154
AWS SDK for Ruby Developer Guide AWS SDK for Ruby: Developer Guide Copyright © 2020 Amazon Web Services, Inc. and/or its affiliates. All rights reserved.

Upload: others

Post on 06-Jun-2020

42 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: AWS SDK for Ruby › sdk-for-ruby › latest › ...AWS SDK for Ruby to create Ruby applications that use AWS services. This guide contains the following sections: Getting Started

AWS SDK for RubyDeveloper Guide

AWS SDK for Ruby: Developer GuideCopyright © 2020 Amazon Web Services, Inc. and/or its affiliates. All rights reserved.

Page 2: AWS SDK for Ruby › sdk-for-ruby › latest › ...AWS SDK for Ruby to create Ruby applications that use AWS services. This guide contains the following sections: Getting Started

AWS SDK for Ruby Developer Guide

Amazon's trademarks and trade dress may not be used in connection with any product or service that is notAmazon's, in any manner that is likely to cause confusion among customers, or in any manner that disparages ordiscredits Amazon. All other trademarks not owned by Amazon are the property of their respective owners, who mayor may not be affiliated with, connected to, or sponsored by Amazon.

Page 3: AWS SDK for Ruby › sdk-for-ruby › latest › ...AWS SDK for Ruby to create Ruby applications that use AWS services. This guide contains the following sections: Getting Started

AWS SDK for Ruby Developer Guide

Table of ContentsAWS SDK for Ruby Developer Guide .... . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1

Using the AWS SDK for Ruby with AWS Cloud9 .... . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1About This Guide .... . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1Additional Documentation and Resources .... . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1

Deploying to the AWS Cloud .... . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2Getting Started .... . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3

Quick Start Guide .... . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3Write the Code .... . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3Run the Code .... . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3Note for Windows Users ... . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3

Installing the SDK .... . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4Prerequisites ... . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4Installing the SDK .... . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4

Hello World Tutorial ... . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4Using the AWS SDK for Ruby in Your Program ..... . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5Creating an Amazon S3 Resource .... . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5Creating a Bucket .... . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5Adding a File to the Bucket .... . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5Listing the Contents of a Bucket .... . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5Complete Program ..... . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5Running the Program ..... . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7Next Steps .... . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7

Configuring the SDK .... . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8Get your AWS access keys .... . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8

To get your access key ID and secret access key .... . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8Setting AWS Credentials ... . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8

Setting Shared Credentials ... . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9Setting Credentials Using Environment Variables .... . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9Setting Credentials Using Aws.config .... . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10Changing your Credentials Location .... . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10Setting Credentials in a Client Object ... . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10Setting Credentials Using IAM ..... . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10

Creating an AWS STS Access Token .... . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10Setting a Region .... . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11

Setting the Region Using Environment Variables .... . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11Setting the Region Using Aws.config .... . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11Setting the Region in a Client or Resource Object ... . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11

Setting a Nonstandard Endpoint ... . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11SDK Metrics ... . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12

Authorize SDK Metrics ... . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12Set Up SDK Metrics ... . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14SDK Metric Definitions .... . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16

Using Cloud9 with the SDK .... . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18Step 1: Set up Your AWS Account to Use AWS Cloud9 .... . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18Step 2: Set up Your AWS Cloud9 Development Environment .... . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18Step 3: Set up the AWS SDK for Ruby .... . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18Step 4: Download Example Code .... . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19Step 5: Run Example Code .... . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19

Using the SDK .... . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20Using the AWS SDK for Ruby REPL Tool ... . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20Using the SDK with Ruby on Rails ... . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20Migrating from Version 1 or 2 to Version 3 of the AWS SDK for Ruby .... . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21

Side-by-Side Usage .... . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21General Differences .... . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21

iii

Page 4: AWS SDK for Ruby › sdk-for-ruby › latest › ...AWS SDK for Ruby to create Ruby applications that use AWS services. This guide contains the following sections: Getting Started

AWS SDK for Ruby Developer Guide

Client Differences .... . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21Resource Differences .... . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22

Debugging Tip: Getting Wire Trace Information from a Client .... . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23Stubbing Client Responses and Errors ... . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24

Stubbing Client Responses .... . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24Stubbing Client Errors ... . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25

Paging Response Data .... . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25Paged Responses Are Enumerable .... . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25Handling Paged Responses Manually ... . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25Paged Data Classes .... . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 26

Using Waiters ... . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 26Invoking a Waiter ... . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 26Wait Failures .... . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 26Configuring a Waiter ... . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 27Extending a Waiter ... . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 27

Specifying a Client Timeout Duration .... . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 28Code Examples .... . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29

AWS CloudTrail Examples .... . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29Listing the CloudTrail Trails ... . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29Creating a CloudTrail Trail .. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 30Listing CloudTrail Trail Events .... . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 32Deleting a CloudTrail Trail .. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 33

Amazon CloudWatch Examples .... . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 34Getting Information about All Amazon CloudWatch Alarms .... . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 34Creating an Amazon CloudWatch Alarm ..... . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 35Enabling and Disabling Amazon CloudWatch Alarm Actions .... . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 35Getting Information about Custom Metrics for Amazon CloudWatch .... . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 37Sending Events to Amazon CloudWatch Events .... . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 38

AWS CodeBuild Examples .... . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 41Getting Information about All AWS CodeBuild Projects ... . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 41Building an AWS CodeBuild Project ... . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 41Listing AWS CodeBuild Project Builds .... . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 42

Amazon DynamoDB Examples .... . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 42Getting Information about All Amazon DynamoDB Tables .... . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 43Creating an Amazon DynamoDB Table .... . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 43Adding an Item to an Amazon DynamoDB Table .... . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 44Loading Items from a JSON File into an Amazon DynamoDB Table .... . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 45Reading an Item in an Amazon DynamoDB Table .... . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 46Updating an Amazon DynamoDB Table Item ..... . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 46Deleting an Amazon DynamoDB Table Item ..... . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 47Deleting an Amazon DynamoDB Table .... . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 47

Amazon EC2 Examples .... . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 48Creating an Amazon EC2 VPC .... . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 48Creating an Internet Gateway and Attaching It to a VPC in Amazon EC2 .... . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 49Creating a Public Subnet for Amazon EC2 .... . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 49Creating an Amazon EC2 Route Table and Associating It with a Subnet .... . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 50Using Elastic IP Addresses in Amazon EC2 .... . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 50Creating an Amazon EC2 Security Group .... . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 52Working with Amazon EC2 Security Groups .... . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 52Working with Key Pairs in Amazon EC2 .... . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 55Getting Information about All Amazon EC2 Instances .... . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 58Getting Information about All Amazon EC2 Instances with a Specific Tag Value .... . . . . . . . . . . . . . . . . . . . . 58Getting Information about a Specific Amazon EC2 Instance .... . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 58Creating an Amazon EC2 Instance .... . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 58Stopping an Amazon EC2 Instance .... . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 59Starting an Amazon EC2 Instance .... . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 60Rebooting an Amazon EC2 Instance .... . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 60

iv

Page 5: AWS SDK for Ruby › sdk-for-ruby › latest › ...AWS SDK for Ruby to create Ruby applications that use AWS services. This guide contains the following sections: Getting Started

AWS SDK for Ruby Developer Guide

Managing Amazon EC2 Instances .... . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 60Terminating an Amazon EC2 Instance .... . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 62Getting Information about Regions and Availability Zones for Amazon EC2 .... . . . . . . . . . . . . . . . . . . . . . . . . . 62

AWS Elastic Beanstalk Examples .... . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 64Getting Information about All Applications in AWS Elastic Beanstalk .... . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 65Getting Information about a Specific Application in AWS Elastic Beanstalk .... . . . . . . . . . . . . . . . . . . . . . . . . . . 65Updating a Ruby on Rails Application for AWS Elastic Beanstalk .... . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 65

AWS Identity and Access Management (IAM) Examples .... . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 67Getting Information about IAM Users ... . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 67Listing IAM Users who are Administrators ... . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 68Adding a New IAM User .... . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 71Create User Access Keys for an IAM User .... . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 71Adding a Managed Policy to an IAM User .... . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 71Creating an IAM Role .... . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 72Managing IAM Users ... . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 72Working with IAM Policies ... . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 74Managing IAM Access Keys .... . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 75Working with IAM Server Certificates .... . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 77Managing IAM Account Aliases .... . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 78

AWS KMS Examples .... . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 79Creating a CMK in AWS KMS .... . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 79Encrypting Data in AWS KMS .... . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 80Decrypting a Data Blob in AWS KMS .... . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 80Re-encrypting a Data Blob in AWS KMS .... . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 81

AWS Lambda Examples .... . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 81Displaying Information about All Lambda Functions .... . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 81Creating a Lambda Function .... . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 82Running a Lambda Function .... . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 82Configuring a Lambda Function to Receive Notifications .... . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 84

Amazon Polly Examples .... . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 84Getting a List of Voices .... . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 85Getting a List of Lexicons .... . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 85Synthesizing Speech .... . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 86

Amazon RDS Examples .... . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 87Getting Information about All Amazon RDS Instances .... . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 87Getting Information about All Amazon RDS Snapshots .... . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 87Getting Information about All Amazon RDS Clusters and Their Snapshots .... . . . . . . . . . . . . . . . . . . . . . . . . . . . 88Getting Information about All Amazon RDS Security Groups .... . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 88Getting Information about All Amazon RDS Subnet Groups .... . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 89Getting Information about All Amazon RDS Parameter Groups .... . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 89Creating a Snapshot of an Amazon RDS Instance .... . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 89Creating a Snapshot of an Amazon RDS Cluster ... . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 90

Amazon S3 Examples .... . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 90Getting Information about All Amazon S3 Buckets ... . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 91Getting Information about All Amazon S3 Buckets in a Region .... . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 91Creating and Using an Amazon S3 Bucket .... . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 91Determining Whether an Amazon S3 Bucket Exists ... . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 95Getting Information about Amazon S3 Bucket Items .... . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 96Uploading an Item to an Amazon S3 Bucket .... . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 96Uploading an Item with Metadata to an Amazon S3 Bucket .... . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 96Downloading an Object from an Amazon S3 Bucket into a File ... . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 97Changing the Properties for an Amazon S3 Bucket Item ..... . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 97Encrypting Amazon S3 Bucket Items .... . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 98Triggering a Notification When an Item is Added to an Amazon S3 Bucket .... . . . . . . . . . . . . . . . . . . . . . . . . . 107Creating a LifeCycle Rule Configuration Template for an Amazon S3 Bucket .... . . . . . . . . . . . . . . . . . . . . . . 108Creating an Amazon S3 Bucket Policy with Ruby .... . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 110Configuring an Amazon S3 Bucket for CORS .... . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 113

v

Page 6: AWS SDK for Ruby › sdk-for-ruby › latest › ...AWS SDK for Ruby to create Ruby applications that use AWS services. This guide contains the following sections: Getting Started

AWS SDK for Ruby Developer Guide

Managing Amazon S3 Bucket and Object Access Permissions .... . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 116Using a Amazon S3 Bucket to Host a Website .... . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 119

Amazon SES Examples .... . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 122Listing Valid Amazon SES Email Addresses .... . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 122Verifying an Email Address in Amazon SES .... . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 123Sending a Message to an Email Address in Amazon SES .... . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 123Getting Amazon SES Statistics ... . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 125

Amazon SNS Examples .... . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 125Getting Information about All Amazon SNS Topics ... . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 126Creating an Amazon SNS Topic ... . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 126Getting Information about All Subscriptions in an Amazon SNS Topic ... . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 126Creating a Subscription in an Amazon SNS Topic ... . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 126Sending a Message to All Amazon SNS Topic Subscribers ... . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 127Enabling a Resource to Publish to an Amazon SNS Topic ... . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 127

Amazon SQS Examples .... . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 128Getting Information about All Queues in Amazon SQS .... . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 128Creating a Queue in Amazon SQS .... . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 129Working with Queues in Amazon SQS .... . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 129Sending Messages in Amazon SQS .... . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 130Sending and Receiving Messages in Amazon SQS .... . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 131Receiving Messages in Amazon SQS .... . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 132Receiving Messages Using Long Polling in Amazon SQS .... . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 133Enabling Long Polling in Amazon SQS .... . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 133Receiving Messages Using the QueuePoller Class in Amazon SQS .... . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 135Redirecting Dead Letters in Amazon SQS .... . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 136Deleting a Queue in Amazon SQS .... . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 136Enabling a Resource to Publish to a Queue in Amazon SQS .... . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 137Working with a Dead Letter Queue in Amazon SQS .... . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 137Specifying the Message Visibility Timeout in Amazon SQS .... . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 139

Amazon WorkDocs Examples .... . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 140Listing Users ... . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 141Listing User Docs .... . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 141

Tips and Tricks .... . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 143Amazon EC2 Tips and Tricks .... . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 143

Switching Elastic IPs ... . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 143Security ... . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 144

Data Protection .... . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 144Identity and Access Management .... . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 145Compliance Validation .... . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 145Resilience .... . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 146Infrastructure Security ... . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 146Using TLS 1.2 .... . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 146

Checking OpenSSL version .... . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 147Upgrading TLS Support ... . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 147

Document History .... . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 148

vi

Page 7: AWS SDK for Ruby › sdk-for-ruby › latest › ...AWS SDK for Ruby to create Ruby applications that use AWS services. This guide contains the following sections: Getting Started

AWS SDK for Ruby Developer GuideUsing the AWS SDK for Ruby with AWS Cloud9

AWS SDK for Ruby Developer GuideWelcome to the AWS SDK for Ruby.

The AWS SDK for Ruby helps take the complexity out of coding by providing Ruby classes for almost allAWS services, including Amazon Simple Storage Service, Amazon Elastic Compute Cloud, and AmazonDynamoDB. For a complete list of services supported by the AWS SDK for Ruby, see the SupportedServices section of the AWS SDK for Ruby Readme file. This section also lists the gems that the AWS SDKfor Ruby supports as version 3 modularized the monolithic SDK gem into service-specific gems.

Using the AWS SDK for Ruby with AWS Cloud9AWS Cloud9 is a web-based integrated development environment (IDE) that contains a collection oftools that you use to code, build, run, test, debug, and release software in the cloud.

See Using AWS Cloud9 with the AWS SDK for Ruby (p. 18) for information on using AWS Cloud9 withthe AWS SDK for Ruby.

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

This guide contains the following sections:

Getting Started with the AWS SDK for Ruby (p. 3)

Describes how to install, configure, and use the AWS SDK for Ruby.Configuring the AWS SDK for Ruby (p. 8)

Steps you through how to configure the AWS SDK for Ruby.Using the AWS SDK for Ruby (p. 20)

Provides general information about developing applications with the AWS SDK for Ruby.AWS SDK for Ruby Code Examples (p. 29)

Provides code examples for programming AWS services with the AWS SDK for Ruby. You can browsethe AWS SDK for Ruby examples in the AWS Code Sample Catalog.

AWS SDK for Ruby Tips and Tricks (p. 143)

Provides helpful information for using the AWS SDK for Ruby with AWS services.Document History (p. 148)

Describes the history of this document.

Additional Documentation and ResourcesFor more resources for AWS SDK for Ruby developers, see the following:

1

Page 8: AWS SDK for Ruby › sdk-for-ruby › latest › ...AWS SDK for Ruby to create Ruby applications that use AWS services. This guide contains the following sections: Getting Started

AWS SDK for Ruby Developer GuideDeploying to the AWS Cloud

• AWS SDK for Ruby API Reference - Version 3• 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 logs under each gem• Moving from v1 to v2• Moving from v2 to v3• Issues• Core upgrade notes

Deploying to the AWS CloudYou can use AWS services such as AWS Elastic Beanstalk, AWS OpsWorks, and CodeDeploy to deployyour application to the AWS Cloud. For deploying Ruby applications with Elastic Beanstalk, seeDeploying Elastic Beanstalk Applications in Ruby Using EB CLI and Git in the AWS Elastic BeanstalkDeveloper Guide. For deploying a Ruby on Rails application with AWS OpsWorks, see Deploying Rubyon Rails Applications to AWS OpsWorks. For an overview of AWS deployment services, see Overview ofDeployment Options on AWS.

2

Page 9: AWS SDK for Ruby › sdk-for-ruby › latest › ...AWS SDK for Ruby to create Ruby applications that use AWS services. This guide contains the following sections: Getting Started

AWS SDK for Ruby Developer GuideQuick Start Guide

Getting Started with the AWS SDKfor Ruby

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

Topics• QuickStart Guide to Using the AWS SDK for Ruby (p. 3)• Installing the AWS SDK for Ruby (p. 4)• Hello World Tutorial for the AWS SDK for Ruby (p. 4)

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

• If you haven’t installed the SDK, see Installing the AWS SDK for Ruby (p. 4).• If you haven’t configured the SDK, see Configuring the AWS SDK for Ruby (p. 8).

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

require 'aws-sdk-s3' # v2: 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 CodeEnter the following command to execute buckets.rb.

ruby buckets.rb

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

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

3

Page 10: AWS SDK for Ruby › sdk-for-ruby › latest › ...AWS SDK for Ruby to create Ruby applications that use AWS services. This guide contains the following sections: Getting Started

AWS SDK for Ruby Developer GuideInstalling the SDK

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

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

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

Aws.use_bundled_cert!

Note that if you are using just the aws-sdk-s3 gem in your Ruby program, you’ll also need to add theaws-sdk-core gem to use the bundled certificate.

Installing the AWS SDK for RubyThis section includes prerequisites and installation instructions for the AWS SDK for Ruby.

PrerequisitesBefore 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.

1. Open http://aws.amazon.com/ and choose Create an AWS Account.2. Follow the online instructions.

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

gem 'aws-sdk'

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

gem install aws-sdk

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

sudo gem install aws-sdk

Hello World Tutorial for the AWS SDK for RubyThis tutorial shows you how to use the AWS SDK for Ruby to create a command line program thatperforms some common Amazon S3 operations.

4

Page 11: AWS SDK for Ruby › sdk-for-ruby › latest › ...AWS SDK for Ruby to create Ruby applications that use AWS services. This guide contains the following sections: Getting Started

AWS SDK for Ruby Developer GuideUsing the AWS SDK for Ruby in Your Program

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

require 'aws-sdk'

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

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

Creating a BucketTo store anything on Amazon S3, you need a bucket to put it in.

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

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

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

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

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

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

Complete ProgramThe following is the entire hello-s3.rb program.

require 'aws-sdk'

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

5

Page 12: AWS SDK for Ruby › sdk-for-ruby › latest › ...AWS SDK for Ruby to create Ruby applications that use AWS services. This guide contains the following sections: Getting Started

AWS SDK for Ruby Developer GuideComplete Program

USAGE = <<DOC

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

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

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

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

DOC

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

if ARGV.length > 0 bucket_name = ARGV[0]else puts USAGE exit 1end

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

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

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

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

case operationwhen 'create' # Create a bucket if it doesn't already 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 the bucket if bucket.object(name).exists? puts "#{name} already exists in the bucket" else obj = s3.bucket(bucket_name).object(name)

6

Page 13: AWS SDK for Ruby › sdk-for-ruby › latest › ...AWS SDK for Ruby to create Ruby applications that use AWS services. This guide contains the following sections: Getting Started

AWS SDK for Ruby Developer GuideRunning the Program

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 USAGEend

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

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

To create a bucket, use the following command, where bucket-name is the name of the bucket youwant 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 doesnot create another copy.

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

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

Next StepsNow that you’ve completed your first AWS SDK for Ruby application, here are some suggestions toextend 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 (p. 5) to confirm the item exists in the bucket, and then

update that bucket item.

7

Page 14: AWS SDK for Ruby › sdk-for-ruby › latest › ...AWS SDK for Ruby to create Ruby applications that use AWS services. This guide contains the following sections: Getting Started

AWS SDK for Ruby Developer GuideGet your AWS access keys

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

Get your AWS access keysAccess keys consist of an access key ID and secret access key, which are used to sign programmaticrequests that you make to AWS. If you don’t have access keys, you can create them by using the AWSManagement Console. We recommend that you use IAM access keys instead of AWS root account accesskeys. IAM lets you securely control access to AWS services and resources in your AWS account.

NoteTo create access keys, you must have permissions to perform the required IAM actions. For moreinformation, see Granting IAM User Permission to Manage Password Policy and Credentials inthe IAM User Guide.

To get your access key ID and secret access key1. Open the IAM console.2. On the navigation menu, choose Users.3. Choose your IAM user name (not the check box).4. Open the Security credentials tab, and then choose Create access key.5. To see the new access key, choose Show. Your credentials resemble the following:

• Access key ID: AKIAIOSFODNN7EXAMPLE• Secret access key: wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY

6. To download the key pair, choose Download .csv file. Store the keys

in a secure location.

ImportantKeep the keys confidential to protect your AWS account, and never email them. Do not sharethem outside your organization, even if an inquiry appears to come from AWS or Amazon.com.No one who legitimately represents Amazon will ever ask you for your secret key.

Related topics

• What Is IAM? in IAM User Guide.• AWS Security Credentials in Amazon Web Services General Reference.

Setting AWS CredentialsBefore you can use the AWS SDK for Ruby to make a call to an AWS service, you must set the AWS accesscredentials 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:

8

Page 15: AWS SDK for Ruby › sdk-for-ruby › latest › ...AWS SDK for Ruby to create Ruby applications that use AWS services. This guide contains the following sections: Getting Started

AWS SDK for Ruby Developer GuideSetting Shared Credentials

1. Setting Credentials Using Environment Variables (p. 9)2. Setting Shared Credentials (p. 9)3. Setting Credentials Using IAM (p. 10)

You can override these settings in your code. The precedence is:

1. Setting Credentials in a Client Object (p. 10)2. Setting Credentials Using Aws.config (p. 10)

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

Note that the shared configuration is loaded only a single time, and credentials are provided statically atclient creation time. Shared credentials do not refresh.

Setting Shared CredentialsSet 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 configurationprofile given to these credentials, your_access_key_id is the value of your access key, andyour_secret_access_key is the value of your secret access key.

[default]aws_access_key_id = your_access_key_idaws_secret_access_key = your_secret_access_key

Setting Credentials Using Environment VariablesSet the AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY environment variables.

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

export AWS_ACCESS_KEY_ID=your_access_key_idexport AWS_SECRET_ACCESS_KEY=your_secret_access_key

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

set AWS_ACCESS_KEY_ID=your_access_key_idset AWS_SECRET_ACCESS_KEY=your_secret_access_key

9

Page 16: AWS SDK for Ruby › sdk-for-ruby › latest › ...AWS SDK for Ruby to create Ruby applications that use AWS services. This guide contains the following sections: Getting Started

AWS SDK for Ruby Developer GuideSetting Credentials Using Aws.config

Setting Credentials Using Aws.configSet 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 yoursecret access key to your_secret_access_key. Any client or resource you create subsequently will usethese credentials.

Aws.config.update({ credentials: Aws::Credentials.new('your_access_key_id', 'your_secret_access_key')})

Changing your Credentials LocationYou can also use Aws.config to store your credentials in a non-standard location.

The following example updates your configuration to store your credentials at my-path.

shared_creds = Aws::SharedCredentials.new(path: 'my_path')Aws.config.update(credentials: shared_creds)

Setting Credentials in a Client ObjectSet 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 thesecret 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 IAMFor an Amazon Elastic Compute Cloud instance, create an AWS Identity and Access Management role,and then give your Amazon EC2 instance access to that role. For more information, see IAM Roles forAmazon EC2 in the Amazon EC2 User Guide for Linux Instances or IAM Roles for Amazon EC2 in theAmazon EC2 User Guide for Windows Instances.

Creating an AWS STS Access TokenUse the Aws::AssumeRoleCredentials method to create an AWS Security Token Service (AWS STS) accesstoken.

The following example uses an access token to create an Amazon S3 client object, wherelinked::account::arn is the Amazon Resource Name (ARN) of the role to assume 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")

10

Page 17: AWS SDK for Ruby › sdk-for-ruby › latest › ...AWS SDK for Ruby to create Ruby applications that use AWS services. This guide contains the following sections: Getting Started

AWS SDK for Ruby Developer GuideSetting a Region

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

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

• Setting the Region in a Client or Resource Object (p. 11)• Setting the Region Using Aws.config (p. 11)• Setting the Region Using Environment Variables (p. 11)

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

Setting the Region Using Environment VariablesSet the region by setting the AWS_REGION environment variable.

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

export AWS_REGION=us-west-2

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

set AWS_REGION=us-west-2

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

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

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

Setting the Region in a Client or Resource ObjectSet the region when you create an AWS client or resource. The following example creates an Amazon S3resource object in the us-west-1 region.

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

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

11

Page 18: AWS SDK for Ruby › sdk-for-ruby › latest › ...AWS SDK for Ruby to create Ruby applications that use AWS services. This guide contains the following sections: Getting Started

AWS SDK for Ruby Developer GuideSDK Metrics

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

SDK Metrics in the AWS SDK for RubyAWS SDK Metrics for Enterprise Support (SDK Metrics) enables enterprise customers to collect metricsfrom AWS SDKs on their hosts and clients shared with AWS Enterprise Support. SDK Metrics providesinformation that helps speed up detection and diagnosis of issues occurring in connections to AWSservices for AWS Enterprise Support customers.

As telemetry is collected on each host, it is relayed via UDP to localhost, where the CloudWatch agentaggregates the data and sends it to the SDK Metrics service. Therefore, to receive metrics, you must addthe CloudWatch agent to your instance.

The following topics describe how to authorize, set up and configure, and define SDK Metrics in the AWSSDK for Ruby.

Topics• Authorize SDK Metrics to Collect and Send Metrics in the AWS SDK for Ruby (p. 12)• Set up SDK Metrics in the AWS SDK for Ruby (p. 14)• Definitions for SDK Metrics (p. 16)

Authorize SDK Metrics to Collect and Send Metrics inthe AWS SDK for RubyTo collect metrics from AWS SDKs using SDK Metrics for Enterprise Support, Enterprise customers mustcreate an IAM Role that gives CloudWatch agent permission to gather data from their Amazon EC2instance or production environment.

Use the following Ruby code sample or the AWS Console to create an IAM Policy and Role for anCloudWatch agent to access SDK Metrics in your environment.

Learn more about using SDK Metrics with AWS SDK for Ruby in Set up SDK Metrics in the AWS SDK forRuby (p. 14).

Set Up Access Permissions Using the AWS SDK for RubyCreate an IAM role for the instance that has permission for Amazon EC2 Systems Manager and SDKMetrics.

First, create a policy using CreatePolicy. Then create a role using CreateRole. Finally, attach the policy youcreated to your new role with AttachRolePolicy.

require 'aws-sdk-iam' # v2: require 'aws-sdk'

role_name = 'AmazonCSM'

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

csm_policy = { 'Version': '2012-10-17', 'Statement': [ {

12

Page 19: AWS SDK for Ruby › sdk-for-ruby › latest › ...AWS SDK for Ruby to create Ruby applications that use AWS services. This guide contains the following sections: Getting Started

AWS SDK for Ruby Developer GuideAuthorize SDK Metrics

'Effect': 'Allow', 'Action': [ 'sdkmetrics:*' ], 'Resource': '*' }, { 'Effect': 'Allow', 'Action': [ 'ssm:GetParameter' ], 'Resource': 'arn:aws:ssm:*:*:parameter/AmazonCSM*' } ]}

# Create policyresp = client.create_policy({ policy_name: role_name, policy_document: csm_policy.to_json, })

policy_arn = resp.policy.arn

puts 'Created policy with ARN: ' + policy_arn

policy_doc = { Version: '2012-10-17', Statement: [ { Effect: 'Allow', Principal: { Service: 'ec2.amazonaws.com' }, Action: 'sts:AssumeRole' },]}

# Create roleclient.create_role( { role_name: role_name, description: 'An instance role that has permission for AWS Systems Manager and SDK Metric Monitoring.', assume_role_policy_document: policy_doc.to_json, })

puts 'Created role ' + role_name

# Attach policy to roleclient.attach_role_policy( { policy_arn: policy_arn, role_name: role_name, })

puts 'Attached policy ' + role_name + 'policy to role: ' + role_name

Set Up Access Permissions by Using the IAM ConsoleAlternatively, you can use the IAM console to create a role.

1. Go to the IAM console, and create a role to use Amazon EC2.2. In the navigation pane, choose Roles.

13

Page 20: AWS SDK for Ruby › sdk-for-ruby › latest › ...AWS SDK for Ruby to create Ruby applications that use AWS services. This guide contains the following sections: Getting Started

AWS SDK for Ruby Developer GuideSet Up SDK Metrics

3. Choose Create Role.4. Choose AWS Service, and then EC2.5. Choose Next: Permissions.6. Under Attach permissions policies, choose create policy.7. For Service, choose Systems Manager. For Actions, expand Read, and choose GetParameters. For

resources, specify your CloudWatch agent.8. Add additional permission.9. Select Choose a service, and then Enter service manually. For Service, enter sdkmetrics. Select all

sdkmetrics actions and all resources, and then choose Review Policy.10.Name the Role AmazonSDKMetrics, and add a description.11.Choose Create Role.

Set up SDK Metrics in the AWS SDK for RubyThe following steps demonstrate how to set up SDK Metrics for the AWS SDK for Ruby. These stepspertain to an Amazon EC2 instance running Amazon Linux for a client application that is using the AWSSDK for Ruby. SDK Metrics is also available for your production environments if you enable it whileconfiguring the AWS SDK for Ruby.

To use SDK Metrics, run the latest version of the CloudWatch agent.

For details about IAM Permissions for SDK Metrics, see Authorize SDK Metrics to Collect and Send Metricsin the AWS SDK for Ruby (p. 12).

To set up SDK Metrics with the AWS SDK for Ruby:

1. Create an application with an AWS SDK for Ruby client to use an AWS service.2. Host your project on an Amazon EC2 instance or in your local environment.3. Install and use the latest version of the AWS SDK for Ruby.4. Install and configure a CloudWatch agent on an Amazon EC2 instance or in your local environment.5. Authorize SDK Metrics to collect and send metrics.6. Enable SDK Metrics for the AWS SDK for Ruby (p. 14).

For more information, see:

• Update a CloudWatch Agent (p. 15).• Disable SDK Metrics (p. 16).

Enable SDK Metrics for the AWS SDK for RubyBy default, SDK Metrics is turned off, and the port is set to 31000. The following are the defaultparameters.

//default values[ 'enabled' => false, 'port' => 31000,]

Enabling SDK Metrics is independent of configuring your credentials to use an AWS service.

You can enable SDK Metrics by setting environment variables or by using the AWS Shared config file.

14

Page 21: AWS SDK for Ruby › sdk-for-ruby › latest › ...AWS SDK for Ruby to create Ruby applications that use AWS services. This guide contains the following sections: Getting Started

AWS SDK for Ruby Developer GuideSet Up SDK Metrics

Option 1: Set Environment Variables

The SDK first checks the profile specified in the environment variable under AWS_PROFILE to determineif SDK Metrics is enabled.

To turn on SDK Metrics, add the following to your environmental variables.

export AWS_CSM_ENABLED=true

Other configuration settings are available, see update_cw_agent for details. For more information aboutusing shared files, see the environment variables information in configuring-sdk.

NoteEnabling SDK Metrics does not configure your credentials to use an AWS service. To do that, seespecifying-credentials.

Option 2: AWS Shared Config File

If no SDK Metrics configuration is found in the environment variables, the AWS SDK for Ruby looksfor your customized AWS profile field. Then it checks the aws_csm profile. To enable SDK Metrics, addcsm_enabled to the shared config file ~/.aws/config.

[default]csm_enabled = true

[profile aws_csm]csm_enabled = true

Other configuration settings are available, see update_cw_agent for details. For more information aboutusing shared files, see the environment variables information in configuring-sdk.

NoteEnabling SDK Metrics does not configure your credentials to use an AWS service. To do that, seespecifying-credentials.

Update a CloudWatch AgentTo make changes to the port ID, set the values and then restart any AWS jobs that are currently active.

Option 1: Set Environment Variables

Most AWS services use the default port. But if the service you want SDK Metrics to monitor uses a uniqueport, add AWS_CSM_PORT=[PORT-NUMBER], where PORT-NUMBER is the port number, to the host’senvironment variables.

export AWS_CSM_ENABLED=trueexport AWS_CSM_PORT=1234

Option 2: AWS Shared Config File

Most services use the default port. If your service requires a unique port ID, add AWS_CSM_PORT=[PORT-NUMBER], where PORT-NUMBER is the port number, to ~/.aws/config.

[default]csm_enabled = falsecsm_port = 1234

[profile aws_csm]csm_enabled = false

15

Page 22: AWS SDK for Ruby › sdk-for-ruby › latest › ...AWS SDK for Ruby to create Ruby applications that use AWS services. This guide contains the following sections: Getting Started

AWS SDK for Ruby Developer GuideSDK Metric Definitions

csm_port = 1234

Restart SDK Metrics

To restart a job, run the following commands.

amazon-cloudwatch-agent-ctl -a stop;amazon-cloudwatch-agent-ctl -a start;

Disable SDK MetricsTo turn off SDK Metrics, set csm_enabled to false in your environment variables or in your AWS Sharedconfig file ~/.aws/config. Then restart your CloudWatch agent so that the changes can take effect.

Set csm_enabled to false

Option 1: Environment Variables

export AWS_CSM_ENABLED=false

Option 2: AWS Shared Config File

NoteEnvironment variables override the AWS Shared config file. If SDK Metrics is enabled in theenvironment variables, the SDK Metrics remains enabled.

[default]csm_enabled = false

[profile aws_csm]csm_enabled = false

Stop SDK Metrics and Restart CloudWatch Agent

To disable SDK Metrics, use the following command.

sudo /opt/aws/amazon-cloudwatch-agent/bin/amazon-cloudwatch-agent-ctl -a stop&& echo "Done"

If you are using other CloudWatch features, restart CloudWatch with the following command.

amazon-cloudwatch-agent-ctl -a start;

Definitions for SDK MetricsUse the following descriptions of SDK Metrics to interpret your results. In general, these metrics areavailable for review with your Technical Account Manager during regular business reviews. AWS Supportresources and your Technical Account Manager should have access to SDK Metrics data to help youresolve cases, but if you discover data that is confusing or unexpected, but doesn’t seem to be negativelyimpacting your application’s performance, it is best to review that data during scheduled businessreviews.

Metric Definition How to use it

CallCount Total number of successful orfailed API calls from your codeto AWS services

Use it as a baseline to correlatewith other metrics like errors orthrottling.

16

Page 23: AWS SDK for Ruby › sdk-for-ruby › latest › ...AWS SDK for Ruby to create Ruby applications that use AWS services. This guide contains the following sections: Getting Started

AWS SDK for Ruby Developer GuideSDK Metric Definitions

Metric Definition How to use it

ClientErrorCount Number of API calls that failwith client errors (4xx HTTPresponse codes). Examples:Throttling, Access denied, S3bucket does not exist, andInvalid parameter value.

Except in certain cases related tothrottling (ex. when throttlingoccurs due to a limit that needsto be increased) this metriccan indicate something in yourapplication that needs to befixed.

ConnectionErrorCount Number of API calls that failbecause of errors connecting tothe service. These can be causedby network issues betweenthe customer application andAWS services including loadbalancers, DNS failures, transitproviders. In some cases, AWSissues may result in this error.

Use this metric to determinewhether issues are specificto your application or arecaused by your infrastructureand/or network. HighConnectionErrorCount couldalso indicate short timeoutvalues for API calls.

ThrottleCount Number of API calls that fail dueto throttling by AWS services.

Use this metric to assess ifyour application has reachedthrottle limits, as well asto determine the cause ofretries and application latency.Consider distributing calls over awindow instead of batching yourcalls.

ServerErrorCount Number of API calls that faildue to server errors (5xx HTTPresponse codes) from AWSServices. These are typicallycaused by AWS services.

Determine cause of SDK retriesor latency. This metric willnot always indicate that AWSservices are at fault, as someAWS teams classify latency as anHTTP 503 response.

EndToEndLatency Total time for your applicationto make a call using the AWSSDK, inclusive of retries. In otherwords, regardless of whetherit is successful after severalattempts, or as soon as a callfails due to an unretriable error.

Determine how AWS API callscontribute to your application’soverall latency. Higher thanexpected latency may be causedby issues with network, firewall,or other configuration settings,or by latency that occurs as aresult of SDK retries.

17

Page 24: AWS SDK for Ruby › sdk-for-ruby › latest › ...AWS SDK for Ruby to create Ruby applications that use AWS services. This guide contains the following sections: Getting Started

AWS SDK for Ruby Developer GuideStep 1: Set up Your AWS Account to Use AWS Cloud9

Using AWS Cloud9 with the AWSSDK for Ruby

You can use AWS Cloud9 with the AWS SDK for Ruby to write and run your Ruby code using just abrowser. AWS Cloud9 includes tools such as a code editor and terminal. Because the AWS Cloud9 IDEis cloud based, you can work on your projects from your office, home, or anywhere using an internet-connected machine. For general information about AWS Cloud9, see the AWS Cloud9 User Guide.

Follow these instructions to set up AWS Cloud9 with the AWS SDK for Ruby:

• Step 1: Set up Your AWS Account to Use AWS Cloud9 (p. 18)• Step 2: Set up Your AWS Cloud9 Development Environment (p. 18)• Step 3: Set up the AWS SDK for Ruby (p. 18)• Step 4: Download Example Code (p. 19)• Step 5: Run Example Code (p. 19)

Step 1: Set up Your AWS Account to Use AWSCloud9

Start to use AWS Cloud9 by signing in to the AWS Cloud9 console as an AWS Identity and AccessManagement (IAM) entity (for example, an IAM user) in your AWS account who has access permissions forAWS Cloud9.

To set up an IAM entity in your AWS account to access AWS Cloud9, and to sign in to the AWS Cloud9console, see Team Setup for AWS Cloud9 in the AWS Cloud9 User Guide.

Step 2: Set up Your AWS Cloud9 DevelopmentEnvironment

After you sign in to the AWS Cloud9 console, use the console to create an AWS Cloud9 developmentenvironment. After you create the environment, AWS Cloud9 opens the IDE for that environment.

See Creating an Environment in AWS Cloud9 in the AWS Cloud9 User Guide for details.

NoteAs you create your environment in the console for the first time, we recommend that you choosethe option to Create a new instance for environment (EC2). This option tells AWS Cloud9 tocreate an environment, launch an Amazon EC2 instance, and then connect the new instance tothe new environment. This is the fastest way to begin using AWS Cloud9.

Step 3: Set up the AWS SDK for RubyAfter AWS Cloud9 opens the IDE for your development environment, use the IDE to set up the AWS SDKfor Ruby in your environment, as follows.

18

Page 25: AWS SDK for Ruby › sdk-for-ruby › latest › ...AWS SDK for Ruby to create Ruby applications that use AWS services. This guide contains the following sections: Getting Started

AWS SDK for Ruby Developer GuideStep 4: Download Example Code

1. If the terminal isn’t already open in the IDE, open it. On the menu bar in the IDE, choose Window,New Terminal.

2. Run the following command to install the AWS SDK for Ruby.

sudo gem install aws-sdk

If the IDE can’t find RubyGems, run the following command to install it. (This command assumes youchose the option to Create a new instance for environment (EC2), earlier in this topic.)

sudo yum -y install gem

If the IDE can’t find Ruby, run the following command to install it. (This command assumes you chose theoption to Create a new instance for environment (EC2), earlier in this topic.)

sudo yum -y install ruby

Step 4: Download Example CodeUse the terminal you opened in the previous step to download example code for the AWS SDK for Rubyinto the AWS Cloud9 development environment.

To do this, run the following command. This command downloads a copy of all of the code examplesused in the official AWS SDK documentation into your environment’s root directory.

git clone https://github.com/awsdocs/aws-doc-sdk-examples.git

To find code examples for the AWS SDK for Ruby, use the Environment window to open theENVIRONMENT_NAME/aws-doc-sdk-examples/ruby/example_code directory, whereENVIRONMENT_NAME is the name of your development environment.

To learn how to work with these and other code examples, see AWS SDK for Ruby CodeExamples (p. 29).

Step 5: Run Example CodeTo run code in your AWS Cloud9 development environment, see Run Your Code in the AWS Cloud9 UserGuide.

19

Page 26: AWS SDK for Ruby › sdk-for-ruby › latest › ...AWS SDK for Ruby to create Ruby applications that use AWS services. This guide contains the following sections: Getting Started

AWS SDK for Ruby Developer GuideUsing the AWS SDK for Ruby REPL Tool

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

Topics• Using the AWS SDK for Ruby REPL Tool (p. 20)• Using the SDK with Ruby on Rails (p. 20)• Migrating from Version 1 or 2 to Version 3 of the AWS SDK for Ruby (p. 21)• Debugging Tip: Getting Wire Trace Information from a Client (p. 23)• Stubbing Client Responses and Errors (p. 24)• Paging Response Data (p. 25)• Using Waiters (p. 26)• Specifying a Client Timeout Duration (p. 28)

Using the AWS SDK for Ruby REPL ToolDevelopers can use aws-v3.rb (formerly aws.rb), the interactive command line read-evaluate-printloop (REPL) console tool that is part of the aws-sdk-core gem.

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

Use the following command to install pry.

gem install pry

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

aws-v3.rbaws-v3.rb -v

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

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

Using the SDK with Ruby on RailsRuby on Rails provides a web development framework that makes it easy to create websites with Ruby.

AWS provides the aws-sdk-rails gem to enable easy integration with Rails. You can use AWS ElasticBeanstalk, AWS OpsWorks, AWS CodeDeploy, or the AWS Rails Provisioner to deploy and run your Railsapplications in the AWS Cloud.

For information on installing and using the aws-sdk-rails gem, see the GitHub repository https://github.com/aws/aws-sdk-rails.

20

Page 27: AWS SDK for Ruby › sdk-for-ruby › latest › ...AWS SDK for Ruby to create Ruby applications that use AWS services. This guide contains the following sections: Getting Started

AWS SDK for Ruby Developer GuideMigrating from Version 1 or 2 to

Version 3 of the AWS SDK for Ruby

Migrating from Version 1 or 2 to Version 3 of theAWS SDK for Ruby

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

Side-by-Side UsageIt isn’t necessary to replace the version 1 or 2 of the AWS SDK for Ruby with version 3. You can use themtogether in the same application. See this blog post for more information.

A quick example follows.

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

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

You don’t need to rewrite existing working version 1 or 2 code to start using the version 3 SDK. A validmigration strategy is to only write new code against the version 3 SDK.

General DifferencesVersion 3 differs from version 2 in one important way.

• Each service is available as a separate gem.

Version 2 differs from version 1 in several important ways.

• Different root namespace –Aws versus AWS. This enables side-by-side usage.

• Aws.config– Now a vanilla Ruby hash, instead of a method.

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

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

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

Client DifferencesThere are no differences between the client classes in version 2 and version 3.

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

21

Page 28: AWS SDK for Ruby › sdk-for-ruby › latest › ...AWS SDK for Ruby to create Ruby applications that use AWS services. This guide contains the following sections: Getting Started

AWS SDK for Ruby Developer GuideResource Differences

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

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

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

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

• Aws::SWF::Client– Version 2 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 are renamed in version 2.Others are 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 is now :ssl_ca_bundle

• :ssl_ca_path is now :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, now replaced by :endpoint.

• :user_agent_prefix is now :user_agent_suffix

Resource DifferencesThere are no differences between the resource interfaces in version 2 and version 3.

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

• Separate resource class – In version 2, the service name is a module, not a class. In this module, it is theresource interface:

# version 1s3 = AWS::S3.new

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

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

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

22

Page 29: AWS SDK for Ruby › sdk-for-ruby › latest › ...AWS SDK for Ruby to create Ruby applications that use AWS services. This guide contains the following sections: Getting Started

AWS SDK for Ruby Developer GuideDebugging Tip: Getting Wire

Trace Information from a Client

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

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

Debugging Tip: Getting Wire Trace Informationfrom a Client

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

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

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

require 'aws-sdk'

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

if s3.bucket(ARGV[0]).exists? puts "Bucket #{ARGV[0]} exists"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 ofyour access key. (Returns were added to the HEAD line for readability.)

opening connection to bucket_name.s3-us-west-1.amazonaws.com:443...openedstarting SSL for bucket_name.s3-us-west-1.amazonaws.com:443...SSL established<- "HEAD / HTTP/1.1\r\n Content-Type: \r\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\n Authorization: AWS4-HMAC-SHA256 Credential=ACCESS_KEY/20160121/us-west-1/s3/aws4_request, SignedHeaders=host;x-amz-content-sha256;x-amz-date, Signature=2ca8301c5e829700940d3cc3bca2a3e8d79d177f2c046c34a1a285770db63820\r\n 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"-> "x-amz-id-2: N6BzRLx8b68NmF50g1IxLzT+E4uWPuAIRe7Pl4XKl5STT4tfNO7gBsO8qrrAnG4CbVpU0iIRXmk=\r\n"

23

Page 30: AWS SDK for Ruby › sdk-for-ruby › latest › ...AWS SDK for Ruby to create Ruby applications that use AWS services. This guide contains the following sections: Getting Started

AWS SDK for Ruby Developer GuideStubbing Client Responses and Errors

-> "Content-Type: application/xml\r\n"-> "Transfer-Encoding: chunked\r\n"-> "Date: Thu, 21 Jan 2016 19:17:54 GMT\r\n"-> "Server: AmazonS3\r\n"-> "\r\n"Conn keep-aliveBucket bucket_name exists

Stubbing Client Responses and ErrorsLearn how to stub client responses and client errors in an AWS SDK for Ruby application.

Stubbing Client ResponsesWhen 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 namebucket_names.each do |name| puts nameend

Running this code displays the following.

aws-sdkaws-sdk2

NoteAfter you supply any stubbed data, the default values no longer apply for any remaininginstance 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 anArgumentError exception. For example, if instead of the previous assignment to bucket_data, youused the following:

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

24

Page 31: AWS SDK for Ruby › sdk-for-ruby › latest › ...AWS SDK for Ruby to create Ruby applications that use AWS services. This guide contains the following sections: Getting Started

AWS SDK for Ruby Developer GuideStubbing Client Errors

The AWS SDK for Ruby raises two ArgumentError exceptions.

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

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

require 'aws-sdk'

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

begin s3.head_bucket({bucket: 'aws-sdk'})rescue Exception => ex puts "Caught #{ex.class} error calling 'head_bucket' on 'aws-sdk'"end

Paging Response DataSome AWS calls provide paged responses to limit the amount of data returned with each response. Apage of data represents up to 1,000 items.

Paged Responses Are EnumerableThe 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| puts response.contents.map(&:key)end

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

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

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

s3 = Aws::S3::Client.new

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

# Get additional pages

25

Page 32: AWS SDK for Ruby › sdk-for-ruby › latest › ...AWS SDK for Ruby to create Ruby applications that use AWS services. This guide contains the following sections: Getting Started

AWS SDK for Ruby Developer GuidePaged Data Classes

while response.next_page? do response = response.next_page # Use the response data here...end

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

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

Using WaitersWaiters are utility methods that poll for a particular state to occur on a client. Waiters can fail after anumber of attempts at a polling interval defined for the service client. For an example of how a waiter isused, see Creating an Amazon DynamoDB Table (p. 43).

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

ec2 = Aws::EC2::Client.new

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 whichoperation is being waited for. The second parameter is a hash of parameters that are passed to the clientmethod 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 FailuresWaiters 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.

26

Page 33: AWS SDK for Ruby › sdk-for-ruby › latest › ...AWS SDK for Ruby to create Ruby applications that use AWS services. This guide contains the following sections: Getting Started

AWS SDK for Ruby Developer GuideConfiguring a Waiter

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 awaiter, 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 WaiterEach waiter has a default polling interval and a maximum number of attempts it will make beforereturning control to your program. To set these values, use the max_attempts and delay: parametersin your #wait_until call. The following example waits for up to 25 seconds, polling every five seconds.

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

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

Extending a WaiterTo modify the behavior of waiters, you can register callbacks that are triggered before each pollingattempt and before waiting.

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

ec2 = Aws::EC2::Client.new

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

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

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

# Poll for one hour, instead of a number of attempts w.before_wait do |attempts, response| throw :failure if Time.now - started_at > 3600

27

Page 34: AWS SDK for Ruby › sdk-for-ruby › latest › ...AWS SDK for Ruby to create Ruby applications that use AWS services. This guide contains the following sections: Getting Started

AWS SDK for Ruby Developer GuideSpecifying a Client Timeout Duration

endend

Specifying a Client Timeout DurationBy default, the AWS SDK for Ruby performs up to three retries, with 15 seconds between retries, for atotal of up to four attempts. Therefore, an operation could take up to 60 seconds to time out.

The following example creates an Amazon S3 client in the region us-west-2, and specifies to wait fiveseconds between two retries on every client operation. Therefore, Amazon S3 client operations couldtake up to 15 seconds to time out.

s3 = Aws::S3::Client.new( region: region, retry_limit: 2, retry_backoff: lambda { |c| sleep(5) })

28

Page 35: AWS SDK for Ruby › sdk-for-ruby › latest › ...AWS SDK for Ruby to create Ruby applications that use AWS services. This guide contains the following sections: Getting Started

AWS SDK for Ruby Developer GuideAWS CloudTrail Examples

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

Find the source code for these examples and others in the AWS documentation code examples repositoryon GitHub. To propose a new code example for the AWS documentation team to consider producing,create a new request. The team is looking to produce code examples that cover broader scenarios anduse cases, versus simple code snippets that cover only individual API calls. For instructions, see theProposing new code examples section in the Readme on GitHub.

Topics• CloudTrail Examples Using the AWS SDK for Ruby (p. 29)• Amazon CloudWatch Examples Using the AWS SDK for Ruby (p. 34)• CodeBuild Examples Using the AWS SDK for Ruby (p. 41)• Amazon DynamoDB Examples Using the AWS SDK for Ruby (p. 42)• Amazon EC2 Examples Using the AWS SDK for Ruby (p. 48)• AWS Elastic Beanstalk Examples Using the AWS SDK for Ruby (p. 64)• AWS Identity and Access Management (IAM) Examples Using the AWS SDK for Ruby (p. 67)• AWS Key Management Service Examples Using the AWS SDK for Ruby (p. 79)• AWS Lambda Examples Using the AWS SDK for Ruby (p. 81)• Amazon Polly Examples Using the AWS SDK for Ruby (p. 84)• Amazon RDS Examples Using the AWS SDK for Ruby (p. 87)• Amazon S3 Examples Using the AWS SDK for Ruby (p. 90)• Amazon SES Examples Using the AWS SDK for Ruby (p. 122)• Amazon SNS Examples Using the AWS SDK for Ruby (p. 125)• Amazon SQS Examples Using the AWS SDK for Ruby (p. 128)• Amazon WorkDocs Examples (p. 140)

CloudTrail Examples Using the AWS SDK for RubyCloudTrail is an AWS service that you can use to monitor your AWS deployments in the cloud bygetting a history of AWS API calls for your account. You can use the following AWS SDK for Ruby codeexamples to access AWS CloudTrail. For more information about CloudTrail, see the AWS CloudTraildocumentation.

Topics• Listing the CloudTrail Trails (p. 29)• Creating a CloudTrail Trail (p. 30)• Listing CloudTrail Trail Events (p. 32)• Deleting a CloudTrail Trail (p. 33)

Listing the CloudTrail TrailsThis example uses the describe_trails method to list the names of the CloudTrail trails and the bucket inwhich CloudTrail stores information in the us-west-2 region.

29

Page 36: AWS SDK for Ruby › sdk-for-ruby › latest › ...AWS SDK for Ruby to create Ruby applications that use AWS services. This guide contains the following sections: Getting Started

AWS SDK for Ruby Developer GuideCreating a CloudTrail Trail

Choose Copy to save the code locally.

Create the file describe_trails.rb with the following code.

=begin###############################################################################

Purpose: Lists information about a trail in AWS CloudTrail.

Prerequisites: - You must have an AWS account. For more information, see "How do I create and activate a new Amazon Web Services account" on the AWS Premium Support website. - This code uses default AWS access credentials. For more information, see "Configuring the AWS SDK for Ruby" in the AWS SDK for Ruby Developer Guide.

Running the code: To run this code, use RSpec. For example:

rspec aws-ruby-sdk-cloudtrail-example-describe-trails.rb -f d

Additional information: - As an AWS best practice, grant this code least privilege, or only the permissions required to perform a task. For more information, see "Grant Least Privilege," in the AWS Identity and Access Management User Guide. - This code has not been tested in all AWS Regions. Some AWS services are available only in specific Regions. For more information, see the "AWS Regional Table" on the AWS website. - Running this code outside of the included RSpec tests might result in charges to your AWS account.

See the complete example on GitHub.

Creating a CloudTrail TrailThis example uses the create_trail method to create a CloudTrail trail in the us-west-2 region. Itrequires two inputs, the name of the trail and the name of the bucket in which CloudTrail storesinformation. If the bucket does not have the proper policy, include the -p flag to attach the correct policyto the bucket.

Choose Copy to save the code locally.

Create the file create_trail.rb. Add the following statements to use the CloudTrail, STS, and S3 gems ofthe AWS SDK for Ruby.

=begin###############################################################################

Create a function to add a policy to the bucket that gives CloudTrail permission to save data to thebucket.

Prerequisites: - You must have an AWS account. For more information, see "How do I create and activate a new Amazon Web Services account" on the AWS Premium Support website.

30

Page 37: AWS SDK for Ruby › sdk-for-ruby › latest › ...AWS SDK for Ruby to create Ruby applications that use AWS services. This guide contains the following sections: Getting Started

AWS SDK for Ruby Developer GuideCreating a CloudTrail Trail

- This code uses default AWS access credentials. For more information, see "Configuring the AWS SDK for Ruby" in the AWS SDK for Ruby Developer Guide.

Running the code: To run this code, use RSpec. For example:

rspec aws-ruby-sdk-cloudtrail-example-create-trail.rb -f d

Additional information: - As an AWS best practice, grant this code least privilege, or only the permissions required to perform a task. For more information, see "Grant Least Privilege," in the AWS Identity and Access Management User Guide. - This code has not been tested in all AWS Regions. Some AWS services are available only in specific Regions. For more information, see the "AWS Regional Table" on the AWS website. - Running this code outside of the included RSpec tests might result in charges to your AWS account.

###############################################################################=end

require 'aws-sdk-cloudtrail'require 'aws-sdk-s3'require 'aws-sdk-sts' # Creates a trail in AWS CloudTrail.class CreateTrailExample # Initialize an instance of CreateTrailExample, creating clients for AWS STS, # AWS CloudTrail, and Amazon S3 (unless already provided # during initialization). # # (The following comments express documentation about this function in YARD # format by using @ symbols.) # # @param [Hash] opts ({}) A hash of API clients for S3, STS, and CloudTrail. # @option [Aws::S3::Client] :s3_client (Aws::S3::Client) # @option [Aws::STS::Client] :sts_client (Aws::STS::Client) # @option [Aws::CloudTrail::Client] :cloudtrail_client # (Aws::CloudTrail::Client) def initialize(opts = {}) # This S3 API client is used for :put_bucket_policy. @s3 = opts[:s3_client] || Aws::S3::Client.new # This STS API client is used to get the account ID. @sts = opts[:sts_client] || Aws::STS::Client.new # This CloudTrail API client is used to create the CloudTrail resource.

Get the names of the trail and bucket, and whether to attach the policy to the bucket. If either the trailname or bucket name is missing, display an error message and exit.

# Creates the specified trail in CloudTrail. # Prerequisites: # An existing S3 bucket with the name specified in bucket_name. # # @param trail_name [String] The name of the trail to create. # @param bucket_name [String] The bucket name to associate with the trail. # @param add_bucket_policy [Boolean] (false) Set to true to add a policy # to the bucket if one does not already exist. def create_trail(trail_name, bucket_name, add_bucket_policy = false) if add_bucket_policy account_id = @sts.get_caller_identity.account @s3.put_bucket_policy( bucket: bucket_name,

31

Page 38: AWS SDK for Ruby › sdk-for-ruby › latest › ...AWS SDK for Ruby to create Ruby applications that use AWS services. This guide contains the following sections: Getting Started

AWS SDK for Ruby Developer GuideListing CloudTrail Trail Events

policy: define_policy(bucket_name, account_id) ) end @cloudtrail.create_trail( name: trail_name, s3_bucket_name: bucket_name ) rescue StandardError => e puts "Error in 'create_trail': #{e} (#{e.class})" end private

If the -p flag was specified, call add_policy to attach the policy to the bucket.

# Defines an S3 bucket policy that is compatible with CloudTrail. # Used internally by create_trail. # Prerequisites:

Create the CloudTrail client and call create_trail to create the trail. If any errors occur, print the error andquit, otherwise print a success message.

{ 'Version' => '2012-10-17', 'Statement' => [ { 'Sid' => 'AWSCloudTrailAclCheck20150319', 'Effect' => 'Allow', 'Principal' => { 'Service' => 'cloudtrail.amazonaws.com' }, 'Action' => 's3:GetBucketAcl', 'Resource' => "arn:aws:s3:::#{bucket_name}" }, { 'Sid' => 'AWSCloudTrailWrite20150319',

See the complete example on GitHub.

Listing CloudTrail Trail EventsThis example uses the lookup_events method to list the CloudTrail trail events in the us-west-2 region.

Choose Copy to save the code locally.

Create the file lookup_events.rb. Add the following statement to use the CloudTrail gem of the AWS SDKfor Ruby.

=begin

Create a function to display information about each event.

Purpose: Lists information about events in AWS CloudTrail.

32

Page 39: AWS SDK for Ruby › sdk-for-ruby › latest › ...AWS SDK for Ruby to create Ruby applications that use AWS services. This guide contains the following sections: Getting Started

AWS SDK for Ruby Developer GuideDeleting a CloudTrail Trail

Prerequisites: - You must have an AWS account. For more information, see "How do I create and activate a new Amazon Web Services account" on the AWS Premium Support website. - This code uses default AWS access credentials. For more information, see "Configuring the AWS SDK for Ruby" in the AWS SDK for Ruby Developer Guide.

Running the code: To run this code, use RSpec. For example:

Create a CloudTrail client in us-west-2, call lookup_events, and use the show_event function todisplay information about each event.

Additional information: - As an AWS best practice, grant this code least privilege, or only the permissions required to perform a task. For more information, see "Grant Least Privilege," in the AWS Identity and Access Management User Guide. - This code has not been tested in all AWS Regions. Some AWS services are available only in specific Regions. For more information, see the "AWS Regional Table" on the AWS website. - Running this code outside of the included RSpec tests might result in charges to your AWS account.

See the complete example on GitHub.

Deleting a CloudTrail TrailThis example uses the delete_trail method to delete a CloudTrail trail in the us-west-2 region. Itrequires one input, the name of the trail.

Choose Copy to save the code locally.

Create the file delete_trail.rb with the following code.

=begin###############################################################################

Purpose: Deletes a trail in AWS CloudTrail.

Prerequisites: - You must have an AWS account. For more information, see "How do I create and activate a new Amazon Web Services account" on the AWS Premium Support website. - This code uses default AWS access credentials. For more information, see "Configuring the AWS SDK for Ruby" in the AWS SDK for Ruby Developer Guide.

Running the code: To run this code, use RSpec. For example:

rspec aws-ruby-sdk-cloudtrail-example-delete-trail.rb -f d

Additional information: - As an AWS best practice, grant this code least privilege, or only the permissions required to perform a task. For more information, see "Grant Least Privilege," in the AWS Identity and Access Management User Guide.

33

Page 40: AWS SDK for Ruby › sdk-for-ruby › latest › ...AWS SDK for Ruby to create Ruby applications that use AWS services. This guide contains the following sections: Getting Started

AWS SDK for Ruby Developer GuideAmazon CloudWatch Examples

See the complete example on GitHub.

Amazon CloudWatch Examples Using the AWS SDKfor Ruby

Amazon CloudWatch (CloudWatch) is a monitoring service for AWS cloud resources and the applicationsyou run on AWS. You can use the following examples to access CloudWatch by using the AWS SDK forRuby. For more information about CloudWatch, see the Amazon CloudWatch documentation.

Topics

• Getting Information about All Amazon CloudWatch Alarms (p. 34)

• Creating an Amazon CloudWatch Alarm (p. 35)

• Enabling and Disabling Amazon CloudWatch Alarm Actions (p. 35)

• Getting Information about Custom Metrics for Amazon CloudWatch (p. 37)

• Sending Events to Amazon CloudWatch Events (p. 38)

Getting Information about All Amazon CloudWatchAlarmsThe following example displays information about your Amazon CloudWatch alarms.

require 'aws-sdk-cloudwatch' # v2: require 'aws-sdk'

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

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

resp.metric_alarms.each do |alarm| puts 'Name: ' + alarm.alarm_name puts 'State: ' + alarm.state_value puts ' reason: ' + alarm.state_reason puts 'Metric: ' + alarm.metric_name puts 'Namespace: ' + alarm.namespace puts 'Statistic: ' + alarm.statistic puts 'Dimensions (' + alarm.dimensions.length.to_s + '):'

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

puts 'Period: ' + alarm.period.to_s puts 'Unit: ' + alarm.unit.to_s puts 'Eval periods: ' + alarm.evaluation_periods.to_s puts 'Threshold: ' + alarm.threshold.to_s puts 'Comp operator: ' + alarm.comparison_operator putsend

See the complete example on GitHub.

34

Page 41: AWS SDK for Ruby › sdk-for-ruby › latest › ...AWS SDK for Ruby to create Ruby applications that use AWS services. This guide contains the following sections: Getting Started

AWS SDK for Ruby Developer GuideCreating an Amazon CloudWatch Alarm

Creating an Amazon CloudWatch AlarmThe following example creates a CloudWatch alarm named my-alarm that sends a message through theAmazon SNS topic with the ARN named ARN when the Amazon S3 bucket named my-bucket has morethan 50 items in a 24-hour period.

require 'aws-sdk-cloudwatch' # v2: require 'aws-sdk'

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

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

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

dimensions = []

dimensions << dim1dimensions << dim2

args[:dimensions] = dimensions

args[:statistic] = 'Maximum'

# NumberOfObjects REQUIRES this valueargs[:period] = 86400

# NumberOfObjects REQUIRES this valueargs[:unit] = nil

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

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

cw.put_metric_alarm(args)

See the complete example on GitHub.

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

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.

35

Page 42: AWS SDK for Ruby › sdk-for-ruby › latest › ...AWS SDK for Ruby to create Ruby applications that use AWS services. This guide contains the following sections: Getting Started

AWS SDK for Ruby Developer GuideEnabling and Disabling Amazon CloudWatch Alarm Actions

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.

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

• Installing the AWS SDK for Ruby (p. 4)• Configuring the AWS SDK for Ruby (p. 8)

You also need to replace arn:aws:sns:REGION-ID:ACCOUNT-ID:TOPIC-NAME with the ARN for a validAmazon SNS topic.

Example

require 'aws-sdk-cloudwatch' # v2: require 'aws-sdk'

# Uncomment for Windows.# Aws.use_bundled_cert!

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

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

cw.put_metric_alarm({ alarm_name: alarm_name, alarm_description: "Alarm whenever an average of more than one object exists in the specified Amazon S3 bucket for more than one day.", actions_enabled: true, # Run actions if the alarm's state changes. metric_name: "NumberOfObjects", alarm_actions: [ "arn:aws:sns:REGION-ID:ACCOUNT-ID:TOPIC-NAME" ], # Notify this Amazon SNS topic only if the alarm's state changes to ALARM. namespace: "AWS/S3", statistic: "Average", dimensions: [ { name: "BucketName", value: "my-bucket" }, { name: "StorageType", value: "AllStorageTypes" } ], period: 86400, # Daily (24 hours * 60 minutes * 60 seconds = 86400 seconds). unit: "Count", evaluation_periods: 1, # More than one day. threshold: 1, # One object. comparison_operator: "GreaterThanThreshold" # More than one object.})

# Disable all actions for the alarm.cw.disable_alarm_actions({ alarm_names: [ alarm_name ]})

36

Page 43: AWS SDK for Ruby › sdk-for-ruby › latest › ...AWS SDK for Ruby to create Ruby applications that use AWS services. This guide contains the following sections: Getting Started

AWS SDK for Ruby Developer GuideGetting Information about Custom

Metrics for Amazon CloudWatch

Getting Information about Custom Metrics forAmazon CloudWatchA CloudWatch alarm watches a single metric over a time period you specify. The CloudWatch alarmperforms one or more actions based on the value of the metric, relative to a given threshold over anumber of time periods. For more information, see Creating Amazon CloudWatch Alarms.

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

1. 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.

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

• Installing the AWS SDK for Ruby (p. 4)

• Configuring the AWS SDK for Ruby (p. 8)

Example

require 'aws-sdk-cloudwatch' # v2: require 'aws-sdk'

# Uncomment for Windows.# Aws.use_bundled_cert!

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

# Send custom metrics to Amazon CloudWatch.# In this example, add metrics to the custom namespace "SITE/TRAFFIC":# For the custom dimension named "SiteName", for the value named "example.com", add# "UniqueVisitors" of 5885 and "UniqueVisits" of 8628.# For the custom dimension named "PageURL", for the value named "my-page.html", add# "PageViews" of 18057.cw.put_metric_data({ namespace: "SITE/TRAFFIC", metric_data: [ { metric_name: "UniqueVisitors", dimensions: [ { name: "SiteName", value: "example.com" } ], value: 5885.0, unit: "Count" }, { metric_name: "UniqueVisits", dimensions: [ { name: "SiteName", value: "example.com" } ],

37

Page 44: AWS SDK for Ruby › sdk-for-ruby › latest › ...AWS SDK for Ruby to create Ruby applications that use AWS services. This guide contains the following sections: Getting Started

AWS SDK for Ruby Developer GuideSending Events to Amazon CloudWatch Events

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 EventsCloudWatch Events delivers a near real-time stream of system events that describe changes in AWSresources to AWS Lambda functions or other targets. See What is Amazon CloudWatch Events? to learnmore. In this example, you use the AWS SDK for Ruby with CloudWatch Events to:

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

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

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

4. View the results in Amazon CloudWatch Logs and metricsby using Aws::CloudWatch::Client#get_metric_statistics andAws::CloudWatchLogs::Client#describe_log_streams.

Prerequisites

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

• Installing the AWS SDK for Ruby (p. 4)

• Configuring the AWS SDK for Ruby (p. 8)

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.

38

Page 45: AWS SDK for Ruby › sdk-for-ruby › latest › ...AWS SDK for Ruby to create Ruby applications that use AWS services. This guide contains the following sections: Getting Started

AWS SDK for Ruby Developer GuideSending Events to Amazon CloudWatch Events

3. For a role, select Choose an Existing Role. For the existing role, select lambda_basic_execution.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 Identity andAccess Management 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-cloudwatch' # v2: require 'aws-sdk'

# Uncomment for Windows.# Aws.use_bundled_cert!

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

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

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

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

# The rule will use this pattern to route the event to the target.# This pattern is used whenever an Amazon EC2 instance begins running.event_pattern = { "source" => [ "aws.ec2" ], "detail-type" => [ "EC2 Instance State-change Notification" ], "detail" => { "state" => [ "running" ] }}.to_json

cwe.put_rule({ name: rule_name, 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

39

Page 46: AWS SDK for Ruby › sdk-for-ruby › latest › ...AWS SDK for Ruby to create Ruby applications that use AWS services. This guide contains the following sections: Getting Started

AWS SDK for Ruby Developer GuideSending Events to Amazon CloudWatch Events

} ]})

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

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

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

ec2.stop_instances({ instance_ids: [ instance_id ]})

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

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

ec2.start_instances({ instance_ids: [ instance_id ]})

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

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

invocations = cw.get_metric_statistics({ namespace: "AWS/Events", metric_name: "Invocations", dimensions: [ { name: "RuleName", value: rule_name, }, ], start_time: Time.now - 600, # Look back over the past 10 minutes to see if the rule was triggered (10 minutes * 60 seconds = 600 seconds). end_time: Time.now, period: 60, # Look back every 60 seconds over those past 10 minutes to see how many times the rule may have been triggered. statistics: [ "Sum" ], unit: "Count"})

if invocations.datapoints.count > 0 puts "Rule invocations:" invocations.datapoints.each do |datapoint| puts " #{datapoint.sum} invocation(s) at #{datapoint.timestamp}" endelse 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

40

Page 47: AWS SDK for Ruby › sdk-for-ruby › latest › ...AWS SDK for Ruby to create Ruby applications that use AWS services. This guide contains the following sections: Getting Started

AWS SDK for Ruby Developer GuideAWS CodeBuild Examples

})

get_log_events_response = cwl.get_log_events({ log_group_name: "/aws/lambda/LogEC2InstanceStateChange", log_stream_name: describe_log_streams_response.log_streams[0].log_stream_name # Get the latest log stream only.})

puts "\nLog messages:\n\n"

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

CodeBuild Examples Using the AWS SDK for RubyCodeBuild is a fully managed build service that compiles source code, runs tests, and produces softwarepackages that are ready to deploy. You can use the following AWS SDK for Ruby code examples to accessAWS CodeBuild. For more information about CodeBuild, see the AWS CodeBuild documentation.

Topics

• Getting Information about All AWS CodeBuild Projects (p. 41)

• Building an AWS CodeBuild Project (p. 41)

• Listing AWS CodeBuild Project Builds (p. 42)

Getting Information about All AWS CodeBuildProjectsThe following example lists the names of up to 100 of your AWS CodeBuild projects.

require 'aws-sdk-codebuild' # v2: require 'aws-sdk'

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

resp = client.list_projects({ sort_by: 'NAME', # accepts NAME, CREATED_TIME, LAST_MODIFIED_TIME sort_order: 'ASCENDING' # accepts ASCENDING, DESCENDING})

resp.projects.each { |p| puts p }

puts

Choose Copy to save the code locally. See the complete example on GitHub.

Building an AWS CodeBuild ProjectThe following example builds the AWS CodeBuild project specified on the command line. If no commandline argument is supplied, it emits an error and quits.

require 'aws-sdk-codebuild' # v2: require 'aws-sdk'

41

Page 48: AWS SDK for Ruby › sdk-for-ruby › latest › ...AWS SDK for Ruby to create Ruby applications that use AWS services. This guide contains the following sections: Getting Started

AWS SDK for Ruby Developer GuideListing AWS CodeBuild Project Builds

project_name = ''

if ARGV.length != 1 puts 'You must supply the name of the project to build' exit 1else project_name = ARGV[0]end

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

begin client.start_build(project_name: project_name) puts 'Building project ' + project_namerescue StandardError => ex puts 'Error building project: ' + ex.messageend

Choose Copy to save the code locally. See the complete example on GitHub.

Listing AWS CodeBuild Project BuildsThe following example displays information about your AWS CodeBuild project builds. This informationincludes the name of the project, when the build started, and how long each phase of the build took, inseconds.

require 'aws-sdk-codebuild' # v2: require 'aws-sdk'

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

build_list = client.list_builds({sort_order: 'ASCENDING', })

builds = client.batch_get_builds({ids: build_list.ids})

builds.builds.each do |build| puts 'Project: ' + build.project_name puts 'Phase: ' + build.current_phase puts 'Status: ' + build.build_statusend

Choose Copy to save the code locally. See the complete example on GitHub.

Amazon DynamoDB Examples Using the AWS SDKfor Ruby

Amazon DynamoDB is a fully managed NoSQL database service that provides fast and predictableperformance with seamless scalability. You can use the following examples to access DynamoDB servicesby using the AWS SDK for Ruby. For more information about DynamoDB, see the Amazon DynamoDBdocumentation. Specifically, see Ruby and DynamoDB to learn how to:

• Create a table.

• Load sample data in JSON format.

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

• Run simple queries.

42

Page 49: AWS SDK for Ruby › sdk-for-ruby › latest › ...AWS SDK for Ruby to create Ruby applications that use AWS services. This guide contains the following sections: Getting Started

AWS SDK for Ruby Developer GuideGetting Information about All Amazon DynamoDB Tables

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

Topics

• Getting Information about All Amazon DynamoDB Tables (p. 43)

• Creating an Amazon DynamoDB Table (p. 43)

• Adding an Item to an Amazon DynamoDB Table (p. 44)

• Loading Items from a JSON File into an Amazon DynamoDB Table (p. 45)

• Reading an Item in an Amazon DynamoDB Table (p. 46)

• Updating an Amazon DynamoDB Table Item (p. 46)

• Deleting an Amazon DynamoDB Table Item (p. 47)

• Deleting an Amazon DynamoDB Table (p. 47)

Getting Information about All Amazon DynamoDBTablesThe following example lists the names and number of items in each table in the us-west-2 region.

require 'aws-sdk-dynamodb' # v2: 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 an Amazon DynamoDB TableThe following example creates the table Movies with two required attributes: year and title in theus-west-2 region.

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

require 'aws-sdk-dynamodb' # v2: require 'aws-sdk'

# Create dynamodb client in us-west-2 regiondynamodb = Aws::DynamoDB::Client.new(region: 'us-west-2')

# Create table Movies with year (integer) and title (string)params = { table_name: 'Movies', key_schema: [ { attribute_name: 'year', key_type: 'HASH' #Partition key }, { attribute_name: 'title', key_type: 'RANGE' #Sort key }

43

Page 50: AWS SDK for Ruby › sdk-for-ruby › latest › ...AWS SDK for Ruby to create Ruby applications that use AWS services. This guide contains the following sections: Getting Started

AWS SDK for Ruby Developer GuideAdding an Item to an Amazon DynamoDB Table

], attribute_definitions: [ { attribute_name: 'year', attribute_type: 'N' }, { attribute_name: 'title', attribute_type: 'S' },

], provisioned_throughput: { read_capacity_units: 10, write_capacity_units: 10 }}

begin result = dynamodb.create_table(params)

puts 'Created table. Status: ' + result.table_description.table_status;rescue Aws::DynamoDB::Errors::ServiceError => error puts 'Unable to create table:' puts error.messageend

See the complete example on GitHub.

Adding an Item to an Amazon DynamoDB TableThe following example adds an item with the year 2015 and title The Big New Movie to the Moviestable in the us-west-2 region.

require 'aws-sdk-dynamodb' # v2: require 'aws-sdk'

# Create dynamodb client in us-west-2 regiondynamodb = Aws::DynamoDB::Client.new(region: 'us-west-2')item = { year: 2015, title: 'The Big New Movie', info: { plot: 'Nothing happens at all.', rating: 0 }}

params = { table_name: 'Movie', item: item}

begin dynamodb.put_item(params) puts 'Added movie: ' + year.to_i.to_s + ' - ' + titlerescue Aws::DynamoDB::Errors::ServiceError => error puts 'Unable to add movie:' puts error.messageend

See the complete example on GitHub.

44

Page 51: AWS SDK for Ruby › sdk-for-ruby › latest › ...AWS SDK for Ruby to create Ruby applications that use AWS services. This guide contains the following sections: Getting Started

AWS SDK for Ruby Developer GuideLoading Items from a JSON File

into an Amazon DynamoDB Table

Loading Items from a JSON File into an AmazonDynamoDB TableThe following example adds the items from the JSON file movie_data.json to the Movies table in theus-west-2 region.

require 'aws-sdk-dynamodb' # v2: require 'aws-sdk'require 'json'

# Create dynamodb client in us-west-2 regiondynamodb = Aws::DynamoDB::Client.new(region: 'us-west-2')

file = File.read('movie_data.json')movies = JSON.parse(file)movies.each{|movie|

params = { table_name: 'Movies', item: movie }

begin dynamodb.put_item(params) puts 'Added movie: ' + movie['year'].to_i.to_s + ' - ' + movie['title']

rescue Aws::DynamoDB::Errors::ServiceError => error puts 'Unable to add movie:' puts error.message end}

Here is an example of a JSON file that loads two movies.

[ { "year" : 2013, "title" : "Turn It Down, Or Else!", "info" : { "directors" : [ "Alice Smith", "Bob Jones" ], "release_date" : "2013-01-18T00:00:00Z", "rating" : 6.2, "genres" : [ "Comedy", "Drama" ], "image_url" : "http://ia.media-imdb.com/images/N/O9ERWAU7FS797AJ7LU8HN09AMUP908RLlo5JF90EWR7LJKQ7@@._V1_SX400_.jpg", "plot" : "A rock band plays their music at high volumes, annoying the neighbors.", "rank" : 11, "running_time_secs" : 5215, "actors" : [ "David Matthewman", "Ann Thomas", "Jonathan G. Neff" ] } },

45

Page 52: AWS SDK for Ruby › sdk-for-ruby › latest › ...AWS SDK for Ruby to create Ruby applications that use AWS services. This guide contains the following sections: Getting Started

AWS SDK for Ruby Developer GuideReading an Item in an Amazon DynamoDB Table

{ "year": 2015, "title": "The Big New Movie", "info": { "plot": "Nothing happens at all.", "rating": 0 } }]

See the complete example and the JSON file on GitHub.

Reading an Item in an Amazon DynamoDB TableThe following example displays information about the item with the year 2015 and title The Big NewMovie in the Movies table in the us-west-2 region.

require 'aws-sdk-dynamodb' # v2: require 'aws-sdk'

# Create dynamodb client in us-west-2 regiondynamodb = Aws::DynamoDB::Client.new(region: 'us-west-2')

params = { table_name: 'Movies', key: { year: 2015, title: 'The Big New Movie' }}

begin result = dynamodb.get_item(params)

if result.item == nil puts 'Could not find movie' exit 0 end

puts 'Found movie:' puts ' Year: ' + result.item['year'].to_i.to_s puts ' Title: ' + result.item['title'] puts ' Plot: ' + result.item['info']['plot'] puts ' Rating: ' + result.item['info']['rating'].to_f.to_srescue Aws::DynamoDB::Errors::ServiceError => error puts 'Unable to find movie:' puts error.messageend

See the complete example on GitHub.

Updating an Amazon DynamoDB Table ItemThe following example updates the rating to 0.1 for the item with the year 2015 and title The BigNew Movie in the Movies table in the us-west-2 region.

require 'aws-sdk-dynamodb' # v2: require 'aws-sdk'

# Create dynamodb client in us-west-2 regiondynamodb = Aws::DynamoDB::Client.new(region: 'us-west-2')

46

Page 53: AWS SDK for Ruby › sdk-for-ruby › latest › ...AWS SDK for Ruby to create Ruby applications that use AWS services. This guide contains the following sections: Getting Started

AWS SDK for Ruby Developer GuideDeleting an Amazon DynamoDB Table Item

params = { table_name: 'Movies', key: { year: 2015, title: 'The Big New Movie' }, update_expression: 'set info.rating = :r', expression_attribute_values: {':r' => 0.1}, return_values: 'UPDATED_NEW'}

begin dynamodb.update_item(params) puts 'Rating successfully set'rescue Aws::DynamoDB::Errors::ServiceError => error puts 'Unable to set rating:' puts error.messageend

See the complete example on GitHub.

Deleting an Amazon DynamoDB Table ItemThe following example deletes item with the year 2015 and title The Big New Movie from theMovies table in the us-west-2 region.

require 'aws-sdk-dynamodb' # v2: require 'aws-sdk'

# Create dynamodb client in us-west-2 regiondynamodb = Aws::DynamoDB::Client.new(region: 'us-west-2')

params = { table_name: 'Movies', key: { year: 2015, title: 'The Big New Movie' }}

begin dynamodb.delete_item(params) puts 'Deleted movie'rescue Aws::DynamoDB::Errors::ServiceError => error puts 'Unable to delete movie:' puts error.messageend

See the complete example on GitHub.

Deleting an Amazon DynamoDB TableThe following example deletes the Movies table in the us-west-2 region.

# Create dynamodb client in us-west-2 regiondynamodb = Aws::DynamoDB::Client.new(region: 'us-west-2')

params = { table_name: 'Movies'

47

Page 54: AWS SDK for Ruby › sdk-for-ruby › latest › ...AWS SDK for Ruby to create Ruby applications that use AWS services. This guide contains the following sections: Getting Started

AWS SDK for Ruby Developer GuideAmazon EC2 Examples

}

begin dynamodb.delete_table(params) puts 'Deleted table.'rescue Aws::DynamoDB::Errors::ServiceError => error puts 'Unable to delete table:' puts error.messageend

See the complete example on GitHub.

Amazon EC2 Examples Using the AWS SDK forRuby

Amazon Elastic Compute Cloud (Amazon EC2) is a web service that provides resizeable computingcapacity—literally servers in Amazon’s data centers—that you use to build and host your softwaresystems. You can use the following examples to access Amazon EC2 using the AWS SDK for Ruby. Formore information about Amazon EC2, see the Amazon EC2 Documentation.

Topics

• Creating an Amazon EC2 VPC (p. 48)

• Creating an Internet Gateway and Attaching It to a VPC in Amazon EC2 (p. 49)

• Creating a Public Subnet for Amazon EC2 (p. 49)

• Creating an Amazon EC2 Route Table and Associating It with a Subnet (p. 50)

• Using Elastic IP Addresses in Amazon EC2 (p. 50)

• Creating an Amazon EC2 Security Group (p. 52)

• Working with Amazon EC2 Security Groups (p. 52)

• Working with Key Pairs in Amazon EC2 (p. 55)

• Getting Information about All Amazon EC2 Instances (p. 58)

• Getting Information about All Amazon EC2 Instances with a Specific Tag Value (p. 58)

• Getting Information about a Specific Amazon EC2 Instance (p. 58)

• Creating an Amazon EC2 Instance (p. 58)

• Stopping an Amazon EC2 Instance (p. 59)

• Starting an Amazon EC2 Instance (p. 60)

• Rebooting an Amazon EC2 Instance (p. 60)

• Managing Amazon EC2 Instances (p. 60)

• Terminating an Amazon EC2 Instance (p. 62)

• Getting Information about Regions and Availability Zones for Amazon EC2 (p. 62)

Creating an Amazon EC2 VPCThe following example creates the virtual private cloud (VPC) MyGroovyVPC with the CIDR block10.200.0.0/16. Then it displays the VPC’s ID.

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

48

Page 55: AWS SDK for Ruby › sdk-for-ruby › latest › ...AWS SDK for Ruby to create Ruby applications that use AWS services. This guide contains the following sections: Getting Started

AWS SDK for Ruby Developer GuideCreating an Internet Gateway and

Attaching It to a VPC in Amazon EC2

require 'aws-sdk-ec2' # v2: require 'aws-sdk'

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

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

# So we get a public DNSvpc.modify_attribute({ enable_dns_support: { value: true }})

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

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

puts vpc.vpc_id

Creating an Internet Gateway and Attaching It to aVPC in Amazon EC2The following example creates an internet gateway MyGroovyIGW, attaches it to a VPC that has IDVPC_ID, and then displays the internet gateway’s ID.

require 'aws-sdk-ec2' # v2: 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 for Amazon EC2The following example creates a public subnet MyGroovySubnet in the us-west-2 region and theAvailablity Zone us-west-2a. The example attaches the public subnet to a VPC with the ID VPC_ID thatuses 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' # v2: 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

49

Page 56: AWS SDK for Ruby › sdk-for-ruby › latest › ...AWS SDK for Ruby to create Ruby applications that use AWS services. This guide contains the following sections: Getting Started

AWS SDK for Ruby Developer GuideCreating an Amazon EC2 Route Table

and Associating It with a Subnet

Creating an Amazon EC2 Route Table and AssociatingIt with a SubnetThe following example creates a route table named MyGroovyRouteTable in us-west-2 regionon a VPC with the ID VPC_ID. The route table uses the route with the CIDR block 0.0.0.0/0, andthe gateway with the ID IGW_ID. The example associates the route table with the subnet that has IDSUBNET_ID, and then displays the route table’s ID.

require 'aws-sdk-ec2' # v2: require 'aws-sdk'

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

table = ec2.create_route_table({ vpc_id: VPC_ID })

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

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

table.associate_with_subnet({ subnet_id: SUBNET_ID})

puts table.id

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

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

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

1. Allocate an Elastic IP address by using the Aws::EC2::Client#allocate_address method.2. Associate the address with an Amazon EC2 instance by using the Aws::EC2::Client#associate_address

method.3. Get information about addresses associated with the instance by using the

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

The complete code for this example is available on GitHub.

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

50

Page 57: AWS SDK for Ruby › sdk-for-ruby › latest › ...AWS SDK for Ruby to create Ruby applications that use AWS services. This guide contains the following sections: Getting Started

AWS SDK for Ruby Developer GuideUsing Elastic IP Addresses in Amazon EC2

• Installing the AWS SDK for Ruby (p. 4)• Configuring the AWS SDK for Ruby (p. 8)

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

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

Example

require 'aws-sdk-ec2' # v2: 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 endend

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

puts "\nAllocating the address for the instance..."ec2.allocate_address({ domain: "vpc" })

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

puts "\nAssociating the address with the instance..."ec2.associate_address({ allocation_id: allocate_address_result.allocation_id, instance_id: instance_id, })

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

puts "\nReleasing the address from the instance..."

51

Page 58: AWS SDK for Ruby › sdk-for-ruby › latest › ...AWS SDK for Ruby to create Ruby applications that use AWS services. This guide contains the following sections: Getting Started

AWS SDK for Ruby Developer GuideCreating an Amazon EC2 Security Group

ec2.release_address({ allocation_id: allocate_address_result.allocation_id, })

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

Creating an Amazon EC2 Security GroupThe following example creates a security group named MyGroovySecurityGroup in the us-west-2region on a VPC with the ID VPC_ID. In the example, the security group is allowed access over port22 (SSH) from all addresses (CIDR block 0.0.0.0/0), and is given the description “Security group forMyGroovyInstance”. Then, the security group’s ID is displayed.

require 'aws-sdk-ec2' # v2: 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 Amazon EC2 Security GroupsAn Amazon EC2 security group acts as a virtual firewall that controls the traffic for one or moreinstances. You add rules to each security group to allow traffic to or from its associated instances. Youcan modify the rules for a security group at any time. The new rules are automatically applied to allinstances 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.

52

Page 59: AWS SDK for Ruby › sdk-for-ruby › latest › ...AWS SDK for Ruby to create Ruby applications that use AWS services. This guide contains the following sections: Getting Started

AWS SDK for Ruby Developer GuideWorking with Amazon EC2 Security Groups

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

• Installing the AWS SDK for Ruby (p. 4)• Configuring the AWS SDK for Ruby (p. 8)

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

Configure the SDKFirst you need the AWS SDK for Ruby, and you need to create an EC2 client. Then provide a name for thesecurity group you’ll create. You also need to provide the ID of our VPC, which is available in the consoleafter the VPC is created. Be sure that you replace ``VPC-ID`` with your actual VPC ID.

require 'aws-sdk-ec2' # v2: 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.

You use the security_group_created variable later in the script to determine if a security group wascreated and can therefore be deleted.

Create a Security GroupCreate a security group that allows access over ports 22 (SSH) and 80 (HTTP) from all addresses (CIDRblock 0.0.0.0/0).

# Create a security group.begin create_security_group_result = ec2.create_security_group({ group_name: security_group_name, description: "An example description for my security group.", vpc_id: vpc_id })

# Add rules to the security group. # For example, allow all inbound HTTP and SSH traffic. ec2.authorize_security_group_ingress({ group_id: create_security_group_result.group_id, ip_permissions: [ { ip_protocol: "tcp", from_port: 80, to_port: 80, ip_ranges: [ { cidr_ip: "0.0.0.0/0", } ] }, { ip_protocol: "tcp", from_port: 22,

53

Page 60: AWS SDK for Ruby › sdk-for-ruby › latest › ...AWS SDK for Ruby to create Ruby applications that use AWS services. This guide contains the following sections: Getting Started

AWS SDK for Ruby Developer GuideWorking with Amazon EC2 Security Groups

to_port: 22, ip_ranges: [ { cidr_ip: "0.0.0.0/0", } ] } ] })

security_group_created = truerescue Aws::EC2::Errors::InvalidGroupDuplicate puts "A security group with the name '#{security_group_name}' already exists."end

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

Get Information about a Security GroupHaving created a security group, you output information about your existing security groups and their IPpermissions.

def describe_ip_permission(ip_permission) puts "-" * 22 puts "IP Protocol: #{ip_permission.ip_protocol}" puts "From Port: #{ip_permission.from_port}" puts "To Port: #{ip_permission.to_port}" 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 endend

describe_security_groups_result = ec2.describe_security_groups

describe_security_groups_result.security_groups.each do |security_group| puts "\n" puts "*" * (security_group.group_name.length + 12)

54

Page 61: AWS SDK for Ruby › sdk-for-ruby › latest › ...AWS SDK for Ruby to create Ruby applications that use AWS services. This guide contains the following sections: Getting Started

AWS SDK for Ruby Developer GuideWorking with Key Pairs in Amazon EC2

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) 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 GroupAt the end of the script, assuming that you successfully created a security group and thesecurity_group_created flag is set to true, you 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 in Amazon EC2The following 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 LinuxInstances or Amazon EC2 Key Pairs and Windows Instances in the Amazon EC2 User Guide for WindowsInstances.

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

Create a Key PairCall 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

55

Page 62: AWS SDK for Ruby › sdk-for-ruby › latest › ...AWS SDK for Ruby to create Ruby applications that use AWS services. This guide contains the following sections: Getting Started

AWS SDK for Ruby Developer GuideWorking with Key Pairs in Amazon EC2

})

In this code:

• ec2 is a variable representing an Aws::EC2::Client object.• key_pair_name is a string variable representing the name of the key pair.• key_pair is a variable representing an Aws::EC2::KeyPair object that is returned by calling thecreate_key_pair method.

For more information, see Complete Example (p. 57).

Get Information about Key PairsTo 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 "Created key pair '#{key_pair.key_name}'." puts "\nSHA-1 digest of the DER encoded private key:" puts "#{key_pair.key_fingerprint}" puts "\nUnencrypted PEM encoded RSA private key:" puts "#{key_pair.key_material}"

In this code, key_pair is a variable representing an Aws::EC2::KeyPair object. This is returned by callingthe 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 |kp| puts kp.key_name endend

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 (p. 57).

Delete a Key PairCall the delete_key_pair method, specifying the name of the key pair to delete.

ec2.delete_key_pair({

56

Page 63: AWS SDK for Ruby › sdk-for-ruby › latest › ...AWS SDK for Ruby to create Ruby applications that use AWS services. This guide contains the following sections: Getting Started

AWS SDK for Ruby Developer GuideWorking with Key Pairs in Amazon EC2

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 (p. 57).

Complete ExampleThe following code, which you can adapt and run, combines the preceding examples into a singleexample.

require 'aws-sdk-ec2' # v2: 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 |kp| puts kp.key_name endend

# Delete the key pair.ec2.delete_key_pair({ key_name: key_pair_name })

To run this code, you must:

1. Install the AWS SDK for Ruby. For more information, see Installing the AWS SDK for Ruby (p. 4).

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

57

Page 64: AWS SDK for Ruby › sdk-for-ruby › latest › ...AWS SDK for Ruby to create Ruby applications that use AWS services. This guide contains the following sections: Getting Started

AWS SDK for Ruby Developer GuideGetting Information about All Amazon EC2 Instances

Getting Information about All Amazon EC2 InstancesThe 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' # v2: 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 Amazon EC2 Instanceswith a Specific Tag ValueThe 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.

NoteThe tag name and value are case-sensitive.

require 'aws-sdk-ec2' # v2: 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.nameend

Getting Information about a Specific Amazon EC2InstanceThe following example lists the state of an instance i-123abc in the us-west-2 region.

require 'aws-sdk-ec2' # v2: 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 Amazon EC2 InstanceThe following example creates an Amazon EC2 instance MyGroovyInstance, with the tag Group andvalue MyGroovyGroup. The instance is created in Availability Zone us-west-2a. The instance has the

58

Page 65: AWS SDK for Ruby › sdk-for-ruby › latest › ...AWS SDK for Ruby to create Ruby applications that use AWS services. This guide contains the following sections: Getting Started

AWS SDK for Ruby Developer GuideStopping an Amazon EC2 Instance

machine image MACHINE_IMAGE for the account with ID ACCOUNT_ID, the security group with the IDSECURITY_GROUP_ID, and the subnet with the ID SUBNET_ID. Then it displays the instance’s ID andpublic IP address.

NoteIn the empty script value, you can add instructions that your Amazon EC2 instance executeswhen it starts.

require 'aws-sdk-ec2' # v2: require 'aws-sdk'require 'base64'

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

encoded_script = Base64.encode64(script)

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

instance = ec2.create_instances({ image_id: 'IMAGE_ID', min_count: 1, max_count: 1, key_name: 'MyGroovyKeyPair', security_group_ids: ['SECURITY_GROUP_ID'], user_data: encoded_script, instance_type: 't2.micro', placement: { availability_zone: 'us-west-2a' }, subnet_id: 'SUBNET_ID', iam_instance_profile: { arn: 'arn:aws:iam::' + 'ACCOUNT_ID' + ':instance-profile/aws-opsworks-ec2-role' }})

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

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

puts instance.idputs instance.public_ip_address

Stopping an Amazon EC2 InstanceThe following example stops the instance i-123abc in the us-west-2 region.

require 'aws-sdk-ec2' # v2: 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 80 # stopped

59

Page 66: AWS SDK for Ruby › sdk-for-ruby › latest › ...AWS SDK for Ruby to create Ruby applications that use AWS services. This guide contains the following sections: Getting Started

AWS SDK for Ruby Developer GuideStarting an Amazon EC2 Instance

puts "#{id} is already stopped" else i.stop endend

Starting an Amazon EC2 InstanceThe following example starts the instance i-123abc in the us-west-2 region.

require 'aws-sdk-ec2' # v2: 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 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 endend

Rebooting an Amazon EC2 InstanceThe following example reboots the instance i-123abc in the us-west-2 region.

require 'aws-sdk-ec2' # v2: 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 endend

Managing Amazon EC2 InstancesIn 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.

60

Page 67: AWS SDK for Ruby › sdk-for-ruby › latest › ...AWS SDK for Ruby to create Ruby applications that use AWS services. This guide contains the following sections: Getting Started

AWS SDK for Ruby Developer GuideManaging Amazon EC2 Instances

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

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

• Installing the AWS SDK for Ruby (p. 4)• Configuring the AWS SDK for Ruby (p. 8)

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

Example

require 'aws-sdk-ec2' # v2: 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}" endend

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

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

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

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

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

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

begin monitor_instances_result = ec2.monitor_instances({ instance_ids: [instance_id] }) puts "Detailed monitoring state for instance '#{instance_id}': #{monitor_instances_result.instance_monitorings[0].monitoring.state}"rescue Aws::EC2::Errors::InvalidState puts "Instance '#{instance_id}' is not in a monitorable state. Continuing on..."end

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

describe_instances_result = ec2.describe_instances

61

Page 68: AWS SDK for Ruby › sdk-for-ruby › latest › ...AWS SDK for Ruby to create Ruby applications that use AWS services. This guide contains the following sections: Getting Started

AWS SDK for Ruby Developer GuideTerminating an Amazon EC2 Instance

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 "Architecture: #{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 Amazon EC2 InstanceThe following example terminates the Amazon EC2 instance i-123abc in the us-west-2 region.

require 'aws-sdk-ec2' # v2: 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 endend

Getting Information about Regions and AvailabilityZones for Amazon EC2The following 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 AvailabilityZones in the Amazon EC2 User Guide for Linux Instances.

62

Page 69: AWS SDK for Ruby › sdk-for-ruby › latest › ...AWS SDK for Ruby to create Ruby applications that use AWS services. This guide contains the following sections: Getting Started

AWS SDK for Ruby Developer GuideGetting Information about Regions

and Availability Zones for Amazon EC2

For additional code that you can use to run these examples, see the Complete Example (p. 64).

Get Information about Regions and EndpointsTo get information about available regions, 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 theComplete Example (p. 64).

To get the region names and endpoints:

1. Get an Aws::EC2::Types::DescribeRegionsResult object, which is returned by the describe_regionsmethod and represented in this code by the describe_regions_result variable.

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

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

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

Get Information about Availability ZonesTo get information about Availability Zones, call the describe_availability_zones method.

describe_availability_zones_result = ec2.describe_availability_zones()

The Aws::EC2::Types::DescribeAvailabilityZonesResult object contains an array ofAws::EC2::Types::AvailabilityZone objects representing the Availability Zones. TheDescribeAvailabilityZonesResult object is returned by the describe_availability_zonesmethod 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 theComplete Example (p. 64).

To get the name and state of each Availability Zone, use the AvailabilityZone object’s zone_nameand state attributes.

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

To get any messages about Availability Zones:

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

63

Page 70: AWS SDK for Ruby › sdk-for-ruby › latest › ...AWS SDK for Ruby to create Ruby applications that use AWS services. This guide contains the following sections: Getting Started

AWS SDK for Ruby Developer GuideAWS Elastic Beanstalk Examples

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

Complete ExampleThe following code, which you can adapt and run, combines the preceding examples into a singleexample.

require 'aws-sdk-ec2' # v2: require 'aws-sdk'

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

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

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

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

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

To run this code:

1. Install the AWS SDK for Ruby. For more information, see Installing the AWS SDK for Ruby (p. 4).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 (p. 8). Besure the AWS credentials map to an AWS Identity and Access Management (IAM) entity withaccess to the AWS actions and resources described in this example. This example assumes youhave set the credentials in the AWS credentials profile file or in the AWS_ACCESS_KEY_ID andAWS_SECRET_ACCESS_KEY environment variables on your local system.

AWS Elastic Beanstalk Examples Using the AWSSDK for Ruby

AWS Elastic Beanstalk enables you to quickly deploy and manage applications in the AWS Cloud withoutworrying about the infrastructure that runs those applications. You can use the following examples toaccess Elastic Beanstalk using the AWS SDK for Ruby. For more information about Elastic Beanstalk, seethe AWS Elastic Beanstalk documentation.

Topics• Getting Information about All Applications in AWS Elastic Beanstalk (p. 65)• Getting Information about a Specific Application in AWS Elastic Beanstalk (p. 65)• Updating a Ruby on Rails Application for AWS Elastic Beanstalk (p. 65)

64

Page 71: AWS SDK for Ruby › sdk-for-ruby › latest › ...AWS SDK for Ruby to create Ruby applications that use AWS services. This guide contains the following sections: Getting Started

AWS SDK for Ruby Developer GuideGetting Information about All

Applications in AWS Elastic Beanstalk

Getting Information about All Applications in AWSElastic BeanstalkThe following example lists the names, descriptions, and URLs of all of your Elastic Beanstalkapplications in the us-west-2 region.

require 'aws-sdk-elasticbeanstalk' # v2: require 'aws-sdk'

eb = Aws::ElasticBeanstalk::Client.new(region: 'us-west-2') eb.describe_applications.applications.each do |a| puts "Name: #{a.application_name}" puts "Description: #{a.description}"

eb.describe_environments({application_name: a.application_name}).environments.each do |env| puts " Environment: #{env.environment_name}" puts " URL: #{env.cname}" puts " Health: #{env.health}" endend

Getting Information about a Specific Application inAWS Elastic BeanstalkThe following example lists the name, description, and URL of the MyRailsApp application in the us-west-2 region.

require 'aws-sdk-elasticbeanstalk' # v2: require 'aws-sdk'

eb = Aws::ElasticBeanstalk::Client.new(region: 'us-west-2') app = eb.describe_applications({application_names: [args[0]]})

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

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

Updating a Ruby on Rails Application for AWS ElasticBeanstalkThe following example updates the Ruby on Rails application MyRailsApp in the us-west-2 region.

NoteYou must be in the root of your Rails app to succesfully run the script.

require 'aws-sdk-elasticbeanstalk' # v2: require 'aws-sdk'

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

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

65

Page 72: AWS SDK for Ruby › sdk-for-ruby › latest › ...AWS SDK for Ruby to create Ruby applications that use AWS services. This guide contains the following sections: Getting Started

AWS SDK for Ruby Developer GuideUpdating a Ruby on Rails Application

for AWS Elastic Beanstalk

app_name = 'MyRailsApp'

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

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

# Create new storage locationresp = eb.create_storage_location()

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

s3.list_objects({ prefix: s3_key, bucket: bucket})

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

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

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

key = app_name + "\\" + zip_file_name

s3.put_object({ body: zip_contents, bucket: bucket, key: key})

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

eb.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}"})

eb.update_environment({ environment_name: env_name, version_label: zip_file_basename})

66

Page 73: AWS SDK for Ruby › sdk-for-ruby › latest › ...AWS SDK for Ruby to create Ruby applications that use AWS services. This guide contains the following sections: Getting Started

AWS SDK for Ruby Developer GuideAWS Identity and Access Management (IAM) Examples

AWS Identity and Access Management (IAM)Examples Using the AWS SDK for Ruby

AWS Identity and Access Management (IAM) is a web service for securely controlling access to AWSservices. You can use the following examples to access IAM using the AWS SDK for Ruby. For moreinformation about IAM, see the IAM documentation.

Topics

• Getting Information about IAM Users (p. 67)

• Listing IAM Users who are Administrators (p. 68)

• Adding a New IAM User (p. 71)

• Create User Access Keys for an IAM User (p. 71)

• Adding a Managed Policy to an IAM User (p. 71)

• Creating an IAM Role (p. 72)

• Managing IAM Users (p. 72)

• Working with IAM Policies (p. 74)

• Managing IAM Access Keys (p. 75)

• Working with IAM Server Certificates (p. 77)

• Managing IAM Account Aliases (p. 78)

Getting Information about IAM UsersThe following example lists the groups, policies, and access key IDs of the IAM users in the us-west-2 region. If there are more than 100 users, iam.list_users.IsTruncated is true andiam.list_users.Marker contains a value you can use to get information about additional users. Seethe Aws::IAM::Client.list_users topic for further information.

require 'aws-sdk-iam' # v2: 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 puts " Policies:" iam.list_user_policies({user_name: name}).policy_names.each do |policy| puts " #{policy}" end puts " Access keys:" iam.list_access_keys({user_name: name}).access_key_metadata.each do |key| puts " #{key.access_key_id}" endend

67

Page 74: AWS SDK for Ruby › sdk-for-ruby › latest › ...AWS SDK for Ruby to create Ruby applications that use AWS services. This guide contains the following sections: Getting Started

AWS SDK for Ruby Developer GuideListing IAM Users who are Administrators

Listing IAM Users who are AdministratorsThe following example uses the get_account_authorization_details, method to get the list of users forthe current account.

Choose Copy to save the code locally.

Create the file get_admins.rb.

Add the required IAM gem and the os gem, and use the latter to use the bundled certificate if you arerunning on Microsoft Windows.

NoteVersion 2 of the AWS SDK for Ruby didn’t have service-specific gems.

require 'aws-sdk-iam' # v2: require 'aws-sdk'require 'os'

if OS.windows? Aws.use_bundled_cert!end

Create a method to determine whether the user has a policy with administrator privileges.

def user_has_admin_policy(user, admin_access) policies = user.user_policy_list

policies.each do |p| if p.policy_name == admin_access return true end end falseend

Create a method to determine whether the user has an attached policy with administrator privileges.

def user_has_attached_policy(user, admin_access) attached_policies = user.attached_managed_policies

attached_policies.each do |p| if p.policy_name == admin_access return true end end

falseend

Create a method to determine whether a group to which the user belongs has a policy withadministrator privileges.

def group_has_admin_policy(client, group, admin_access) resp = client.list_group_policies( group_name: group.group_name )

resp.policy_names.each do |name| if name == admin_access

68

Page 75: AWS SDK for Ruby › sdk-for-ruby › latest › ...AWS SDK for Ruby to create Ruby applications that use AWS services. This guide contains the following sections: Getting Started

AWS SDK for Ruby Developer GuideListing IAM Users who are Administrators

return true end end

falseend

Create a method to determine whether a group to which the user belongs has an attached policy withadministrator privileges.

def group_has_attached_policy(client, group, admin_access) resp = client.list_attached_group_policies( group_name: group.group_name # required )

resp.attached_policies.each do |policy| if policy.policy_name == admin_access return true end end

falseend

Create a method to determine whether a group to which the user belongs has administrator privileges.

def user_has_admin_from_group(client, user, admin_access) resp = client.list_groups_for_user( user_name: user.user_name )

resp.groups.each do |group| has_admin_policy = group_has_admin_policy(client, group, admin_access) if has_admin_policy return true end

has_attached_policy = group_has_attached_policy(client, group, admin_access) if has_attached_policy return true end end

falseend

Create a method to determine whether the user has administrator privileges.

def is_user_admin(client, user, admin_access) has_admin_policy = user_has_admin_policy(user, admin_access) if has_admin_policy return true end

has_attached_admin_policy = user_has_attached_policy(user, admin_access) if has_attached_admin_policy return true end

has_admin_from_group = user_has_admin_from_group(client, user, admin_access) if has_admin_from_group return true

69

Page 76: AWS SDK for Ruby › sdk-for-ruby › latest › ...AWS SDK for Ruby to create Ruby applications that use AWS services. This guide contains the following sections: Getting Started

AWS SDK for Ruby Developer GuideListing IAM Users who are Administrators

end

falseend

Create a method to loop through a list of users and return how many of those users have administratorprivileges.

def get_admin_count(client, users, admin_access) num_admins = 0

users.each do |user| is_admin = is_user_admin(client, user, admin_access) if is_admin puts user.user_name num_admins += 1 end end

num_adminsend

The main routine starts here. Create an IAM client and variables to store the number of users, number ofusers who have adminstrator privileges, and the string that identifies a policy that supplies adminstratorprivileges.

client = Aws::IAM::Client.new

num_users = 0num_admins = 0access_admin = 'AdministratorAccess'

Call get_account_authorization_details to get the details of the account and get the users forthe account from user_detail_list. Keep track of how many users we get, call get_admin_count toget the number of those users who have administrator privileges, and keep track of the number of those.

details = client.get_account_authorization_details( filter: ['User'])

users = details.user_detail_listnum_users += users.countmore_admins = get_admin_count(client, users, access_admin)num_admins += more_admins

If the first call to get_account_authorization_details did not get all of the details, call it againand repeat the process of determining how many have administrator privileges.

more_users = details.is_truncated

while more_users details = client.get_account_authorization_details( filter: ['User'], marker: details.marker )

users = details.user_detail_list

num_users += users.count more_admins = get_admin_count(client, users, access_admin)

70

Page 77: AWS SDK for Ruby › sdk-for-ruby › latest › ...AWS SDK for Ruby to create Ruby applications that use AWS services. This guide contains the following sections: Getting Started

AWS SDK for Ruby Developer GuideAdding a New IAM User

num_admins += more_admins

more_users = details.is_truncatedend

Finally, display how many users have administrator privileges.

putsputs "Found #{num_admins} admin(s) out of #{num_users} user(s)"

See the complete example on GitHub.

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

require 'aws-sdk-iam' # v2: 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 User Access Keys for an IAM UserThe following example creates an access key and secret key for the IAM user my_groovy_user in theus-west-2 region.

require 'aws-sdk-iam' # v2: 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

puts "Access key: #{key_pair.access_key_id}" puts "Secret key: #{key_pair.secret}"rescue Aws::IAM::Errors::NoSuchEntity puts 'User does not exist'end

Adding a Managed Policy to an IAM UserThe following example adds the managed policy AmazonS3FullAccess to the IAM usermy_groovy_user in the us-west-2 region.

71

Page 78: AWS SDK for Ruby › sdk-for-ruby › latest › ...AWS SDK for Ruby to create Ruby applications that use AWS services. This guide contains the following sections: Getting Started

AWS SDK for Ruby Developer GuideCreating an IAM Role

require 'aws-sdk-iam' # v2: require 'aws-sdk'

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

policy_arn = prefix + 'AmazonS3FullAccess'

# In case the policy or user does not existbegin client.attach_user_policy({user_name: 'my_groovy_user', policy_arn: policy_arn})rescue Aws::IAM::Errors::NoSuchEntity => ex puts "Error attaching policy '#{policy_arn}'" puts ex.messageend

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

require 'aws-sdk-iam' # v2: require 'aws-sdk'

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

# Let EC2 assume a rolepolicy_doc = { Version:"2012-10-17", Statement:[ { Effect:"Allow", Principal:{ Service:"ec2.amazonaws.com" }, Action:"sts:AssumeRole" }]}

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

# Give the role full access to S3role.attach_policy({ policy_arn: 'arn:aws:iam::aws:policy/AmazonS3FullAccess'})

# Give the role full access to DynamoDBrole.attach_policy({ policy_arn: 'arn:aws:iam::aws:policy/AmazonDynamoDBFullAccess'})

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

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

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

72

Page 79: AWS SDK for Ruby › sdk-for-ruby › latest › ...AWS SDK for Ruby to create Ruby applications that use AWS services. This guide contains the following sections: Getting Started

AWS SDK for Ruby Developer GuideManaging IAM 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.

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

• Installing the AWS SDK for Ruby (p. 4)• Configuring the AWS SDK for Ruby (p. 8)

Example

require 'aws-sdk-iam' # v2: 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 endend

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..."

73

Page 80: AWS SDK for Ruby › sdk-for-ruby › latest › ...AWS SDK for Ruby to create Ruby applications that use AWS services. This guide contains the following sections: Getting Started

AWS SDK for Ruby Developer GuideWorking with IAM Policies

list_user_names(iam)

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

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

1. Create a policy, using Aws::IAM::Client#create_policy.2. Get information about the policy, using Aws::IAM::Client#get_policy.3. Attach the policy to a role, using Aws::IAM::Client#attach_role_policy.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.

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

• Installing the AWS SDK for Ruby (p. 4)• Configuring the AWS SDK for Ruby (p. 8)

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' # v2: 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 })

74

Page 81: AWS SDK for Ruby › sdk-for-ruby › latest › ...AWS SDK for Ruby to create Ruby applications that use AWS services. This guide contains the following sections: Getting Started

AWS SDK for Ruby Developer GuideManaging IAM Access Keys

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}) # List policies attached to the role.puts "\nAttached role policy ARNs..."

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

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

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

Managing IAM Access KeysUsers need their own access keys to make programmatic calls to AWS from the AWS SDK for Ruby. To fillthis need, you can create, modify, view, or rotate access keys (access key IDs and secret access keys) forIAM users. By default, when you create an access key, its status is Active. This means the user can use theaccess 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.

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

• Installing the AWS SDK for Ruby (p. 4)• Configuring the AWS SDK for Ruby (p. 8)

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

Example

require 'aws-sdk-iam' # v2: require 'aws-sdk'

75

Page 82: AWS SDK for Ruby › sdk-for-ruby › latest › ...AWS SDK for Ruby to create Ruby applications that use AWS services. This guide contains the following sections: Getting Started

AWS SDK for Ruby Developer GuideManaging IAM Access Keys

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

user_name = "my-user"

# List user access keys.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_used_date}"

# Deactivate access keys. puts " Trying to deactivate this key..." iam.update_access_key({ user_name: user_name, access_key_id: key_metadata.access_key_id, status: "Inactive" })end

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

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

iam.delete_access_key({

76

Page 83: AWS SDK for Ruby › sdk-for-ruby › latest › ...AWS SDK for Ruby to create Ruby applications that use AWS services. This guide contains the following sections: Getting Started

AWS SDK for Ruby Developer GuideWorking with IAM Server Certificates

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 CertificatesTo enable HTTPS connections to your website or application on AWS, you need an SSL/TLS servercertificate. To use a certificate that you obtained from an external provider with your website orapplication 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.

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

• Installing the AWS SDK for Ruby (p. 4)• Configuring the AWS SDK for Ruby (p. 8)

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

Example

require 'aws-sdk-iam' # v2: require 'aws-sdk'

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

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

# Update a server certificate.iam.update_server_certificate({ server_certificate_name: server_certificate_name, new_server_certificate_name: changed_server_certificate_name})

# Delete the server certificate.iam.delete_server_certificate({ server_certificate_name: changed_server_certificate_name})

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

if list_server_certificates_response.server_certificate_metadata_list.count == 0

77

Page 84: AWS SDK for Ruby › sdk-for-ruby › latest › ...AWS SDK for Ruby to create Ruby applications that use AWS services. This guide contains the following sections: Getting Started

AWS SDK for Ruby Developer GuideManaging IAM Account Aliases

puts "No server certificates."else list_server_certificates_response.server_certificate_metadata_list.each do |certificate_metadata| 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_metadata.server_certificate_id}" endend

Managing IAM Account AliasesIf you want the URL for your sign-in page to contain your company name or other friendly identifierinstead of your AWS account ID, you can create an IAM account alias for your AWS account ID. Ifyou create an IAM account alias, your sign-in page URL changes to incorporate the alias. For moreinformation 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.

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

• Installing the AWS SDK for Ruby (p. 4)• Configuring the AWS SDK for Ruby (p. 8)

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

Example

require 'aws-sdk-iam' # v2: 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

78

Page 85: AWS SDK for Ruby › sdk-for-ruby › latest › ...AWS SDK for Ruby to create Ruby applications that use AWS services. This guide contains the following sections: Getting Started

AWS SDK for Ruby Developer GuideAWS KMS Examples

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)

AWS Key Management Service Examples Using theAWS SDK for Ruby

AWS Key Management Service (AWS KMS) is an encryption and key management service scaled for thecloud. You can use the following examples to access AWS KMS using the AWS SDK for Ruby. For moreinformation about AWS KMS, see the Amazon KMS documentation. For reference information about theAWS KMS client, see Aws::KMS::Client.

Topics• Creating a CMK in AWS KMS (p. 79)• Encrypting Data in AWS KMS (p. 80)• Decrypting a Data Blob in AWS KMS (p. 80)• Re-encrypting a Data Blob in AWS KMS (p. 81)

Creating a CMK in AWS KMSThe following example uses the AWS SDK for Rubycreate_key method, which implements the CreateKeyoperation to create a customer master key (CMK). Because the example only encrypts a small amountof data, a CMK is fine for our purposes. For larger amounts of data, use the CMK to encrypt a dataencryption key (DEK).

require 'aws-sdk-kms' # v2: require 'aws-sdk'

# Create a customer master key (CMK).# As long we are only encrypting small amounts of data (4 KiB or less) directly,# a CMK is fine for our purposes.# For larger amounts of data,# use the CMK to encrypt a data encryption key (DEK).

client = Aws::KMS::Client.new

resp = client.create_key({ tags: [

79

Page 86: AWS SDK for Ruby › sdk-for-ruby › latest › ...AWS SDK for Ruby to create Ruby applications that use AWS services. This guide contains the following sections: Getting Started

AWS SDK for Ruby Developer GuideEncrypting Data in AWS KMS

{ tag_key: 'CreatedBy', tag_value: 'ExampleUser' }, ],})

puts resp.key_metadata.key_id

Choose Copy to save the code locally. See the complete example on GitHub.

Encrypting Data in AWS KMSThe following example uses the AWS SDK for Rubyencrypt method, which implements the Encryptoperation, to encrypt the string “1234567890”. The example displays a readable version of the resultingencrypted blob.

require 'aws-sdk-kms' # v2: require 'aws-sdk'

# ARN of the customer master key (CMK).## Replace the fictitious key ARN with a valid key ID

keyId = 'arn:aws:kms:us-west-2:111122223333:key/1234abcd-12ab-34cd-56ef-1234567890ab'

text = '1234567890'

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

resp = client.encrypt({ key_id: keyId, plaintext: text,})

puts 'Blob:'puts resp.ciphertext_blob.unpack('H*')

Choose Copy to save the code locally. See the complete example on GitHub.

Decrypting a Data Blob in AWS KMSThe following example uses the AWS SDK for Rubydecrypt method, which implements the Decryptoperation, to decrypt the provided string and emit the result.

require 'aws-sdk-kms' # v2: require 'aws-sdk'

# Decrypted blob

blob = '01020200785d68faeec386af1057904926253051eb2919d3c16078badf65b808b26dd057c101747cadf3593596e093d4ffbf22434a6d00000068306606092a864886f70d010706a0593057020100305206092a864886f70d010701301e060960864801650304012e3011040c9d629e573683972cdb7d94b30201108025b20b060591b02ca0deb0fbdfc2f86c8bfcb265947739851ad56f3adce91eba87c59691a9a1'blob_packed = [blob].pack("H*")

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

resp = client.decrypt({ ciphertext_blob: blob_packed})

puts 'Raw text: 'puts resp.plaintext

80

Page 87: AWS SDK for Ruby › sdk-for-ruby › latest › ...AWS SDK for Ruby to create Ruby applications that use AWS services. This guide contains the following sections: Getting Started

AWS SDK for Ruby Developer GuideRe-encrypting a Data Blob in AWS KMS

Choose Copy to save the code locally. See the complete example on GitHub.

Re-encrypting a Data Blob in AWS KMSThe following example uses the AWS SDK for Rubyre_encrypt method, which implements the ReEncryptoperation, to decrypt encrypted data and then immediately re-encrypt data under a new customermaster key (CMK). The operations are performed entirely on the server side within AWS KMS, so theynever expose your plaintext outside of AWS KMS. The example displays a readable version of theresulting re-encrypted blob.

require 'aws-sdk-kms' # v2: require 'aws-sdk'

# Human-readable version of the ciphertext of the data to reencrypt.

blob = '01020200785d68faeec386af1057904926253051eb2919d3c16078badf65b808b26dd057c101747cadf3593596e093d4ffbf22434a6d00000068306606092a864886f70d010706a0593057020100305206092a864886f70d010701301e060960864801650304012e3011040c9d629e573683972cdb7d94b30201108025b20b060591b02ca0deb0fbdfc2f86c8bfcb265947739851ad56f3adce91eba87c59691a9a1'sourceCiphertextBlob = [blob].pack("H*")

# Replace the fictitious key ARN with a valid key ID

destinationKeyId = 'arn:aws:kms:us-west-2:111122223333:key/0987dcba-09fe-87dc-65ba-ab0987654321'

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

resp = client.re_encrypt({ ciphertext_blob: sourceCiphertextBlob, destination_key_id: destinationKeyId})

puts 'Blob:'puts resp.ciphertext_blob.unpack('H*')

Choose Copy to save the code locally. See the complete example on GitHub.

AWS Lambda Examples Using the AWS SDK forRuby

AWS Lambda (Lambda) is a zero-administration compute platform for backend web developers thatruns your code for you in the AWS Cloud, and provides you with a fine-grained pricing structure. You canuse the following examples to access Lambda using the AWS SDK for Ruby. For more information aboutLambda, see the AWS Lambda documentation.

Topics• Displaying Information about All Lambda Functions (p. 81)• Creating a Lambda Function (p. 82)• Running a Lambda Function (p. 82)• Configuring a Lambda Function to Receive Notifications (p. 84)

Displaying Information about All Lambda FunctionsThe following example displays the name, ARN, and role of all of your Lambda functions in the us-west-2 region.

81

Page 88: AWS SDK for Ruby › sdk-for-ruby › latest › ...AWS SDK for Ruby to create Ruby applications that use AWS services. This guide contains the following sections: Getting Started

AWS SDK for Ruby Developer GuideCreating a Lambda Function

require 'aws-sdk-lambda' # v2: require 'aws-sdk'

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

client.list_functions.functions.each do |function| puts 'Name: ' + function.function_name puts 'ARN: ' + function.function_arn puts 'Role: ' + function.role puts

Creating a Lambda FunctionThe following example creates the Lambda function named 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 AWSLambdaExecutemanaged 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-lambda' # v2: require 'aws-sdk'

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

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

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

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

args[:code] = code

client.create_function(args)

Running a Lambda FunctionThe following example runs the Lambda function named MyGetitemsFunction in the us-west-2region. This function returns a list of items from a database. The input JSON looks like the following.

{ "SortBy": "name|time", "SortOrder": "ascending|descending", "Number": 50}

where:

82

Page 89: AWS SDK for Ruby › sdk-for-ruby › latest › ...AWS SDK for Ruby to create Ruby applications that use AWS services. This guide contains the following sections: Getting Started

AWS SDK for Ruby Developer GuideRunning a Lambda Function

• SortBy is the criteria for sorting the results. Our examples uses time, which means the returned itemsare sorted in the order in which they were added to the database.

• SortOrder is the order of sorting. Our example uses descending, which means the most-recent itemis last in the list.

• Number is the maximum number of items to retrieve (the default is 50). Our example uses 10, whichmeans get the 10 most-recent items.

The output JSON looks like the following, where:

• STATUS-CODE is an HTTP status code, 200 means the call was successful.

• RESULT is the result of the call, either success or failure.

• ERROR is an error message if result is failure, otherwise an empty string

• DATA is an array of returned results if result is success, otherwise nil.

{ "statusCode": "STATUS-CODE", "body": { "result": "RESULT", "error": "ERROR", "data": "DATA" }}

The first step is to load the modules we use:

• aws-sdk loads the AWS SDK for Ruby module we use to invoke the Lambda function.

• json loads the JSON module we use to marshall and unmarshall the request and response payloads.

• os loads the OS module we use to ensure we can run our Ruby application on Microsoft Windows. Ifyou are on a different operating system, you can remove those lines.

require 'aws-sdk-lambda' # v2: require 'aws-sdk'require 'json'

# To run on Windows:require 'os'if OS.windows? Aws.use_bundled_cert!end

We then create the Lambda client we use to invoke the Lambda function.

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

Next we create the hash for the request arguments and call MyGetItemsFunction.

req_payload = {:SortBy => 'time', :SortOrder => 'descending', :NumberToGet => 10}payload = JSON.generate(req_payload)

resp = client.invoke({ function_name: 'MyGetItemsFunction', invocation_type: 'RequestResponse', log_type: 'None', payload: payload

83

Page 90: AWS SDK for Ruby › sdk-for-ruby › latest › ...AWS SDK for Ruby to create Ruby applications that use AWS services. This guide contains the following sections: Getting Started

AWS SDK for Ruby Developer GuideConfiguring a Lambda Function to Receive Notifications

})

Finally we parse the response, and if are successful, we print out the items.

resp_payload = JSON.parse(resp.payload.string) # , symbolize_names: true)

# If the status code is 200, the call succeededif resp_payload["statusCode"] == 200 # If the result is success, we got our items if resp_payload["body"]["result"] == "success" # Print out items resp_payload["body"]["data"].each do |item| puts item end endend

See the complete example on GitHub.

Configuring a Lambda Function to ReceiveNotificationsThe following example configures the Lambda function named my-notification-function in theus-west-2 region to accept notifications from the resource with the ARN my-resource-arn.

require 'aws-sdk-lambda' # v2: 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 Polly Examples Using the AWS SDK forRuby

Amazon Polly is a cloud service that converts text into lifelike speech. The AWS SDK for Go examplescan integrate Amazon Polly into your applications. Learn more about Amazon Polly at Amazon Pollydocumentation. The examples assume you have already set up and configured the SDK (that is, you’veimported all required packages and set your credentials and region). For more information, see Installingthe AWS SDK for Ruby (p. 4) and Configuring the AWS SDK for Ruby (p. 8).

You can download complete versions of these example files from the aws-doc-sdk-examples repositoryon GitHub.

Topics• Getting a List of Voices (p. 85)• Getting a List of Lexicons (p. 85)

84

Page 91: AWS SDK for Ruby › sdk-for-ruby › latest › ...AWS SDK for Ruby to create Ruby applications that use AWS services. This guide contains the following sections: Getting Started

AWS SDK for Ruby Developer GuideGetting a List of Voices

• Synthesizing Speech (p. 86)

Getting a List of VoicesThis example uses the describe_voices method to get the list of US English voices in the us-west-2region.

Choose Copy to save the code locally.

Create the file polly_describe_voices.rb.

Add the required gem.

NoteVersion 2 of the AWS SDK for Ruby didn’t have service-specific gems.

require 'aws-sdk-polly' # In v2: require 'aws-sdk'

Create an Amazon Polly client and call describe_voices for US English.

polly = Aws::Polly::Client.newresp = polly.describe_voices(language_code: 'en-US')

Display the name and gender of the voices.

resp.voices.each do |v| puts v.name puts ' ' + v.gender putsend

See the complete example on GitHub.

Getting a List of LexiconsThis example uses the list_lexicons method to get the list of lexicons in the us-west-2 region.

Choose Copy to save the code locally.

Create the file polly_list_lexicons.rb.

Add the required gem.

NoteVersion 2 of the AWS SDK for Ruby didn’t have service-specific gems.

require 'aws-sdk-polly' # In v2: require 'aws-sdk'

Create an Amazon Polly client and call list_lexicons.

polly = Aws::Polly::Client.newresp = polly.list_lexicons

Display the name, alphabet, and language code of each lexicon.

85

Page 92: AWS SDK for Ruby › sdk-for-ruby › latest › ...AWS SDK for Ruby to create Ruby applications that use AWS services. This guide contains the following sections: Getting Started

AWS SDK for Ruby Developer GuideSynthesizing Speech

resp.lexicons.each do |l| puts l.name puts ' Alphabet:' + l.attributes.alphabet puts ' Language:' + l.attributes.language putsend

See the complete example on GitHub.

Synthesizing SpeechThis example uses the synthesize_speech method to get the text from a file and produce an MP3 filecontaining the synthesized speech.

Choose Copy to save the code locally.

Create the file polly_synthesize_speech.rb.

Add the required gem.

NoteVersion 2 of the AWS SDK for Ruby didn’t have service-specific gems.

require 'aws-sdk-polly' # In v2: require 'aws-sdk'

Get the name of the text file from the command line.

if ARGV.empty?() puts 'You must supply a filename' exit 1end

filename = ARGV[0]

Open the text file and read the contents as a string.

contents = IO.read(filename)

Create an Amazon Polly client and call synthesize_speech.

polly = Aws::Polly::Client.newresp = polly.synthesize_speech({ output_format: "mp3", text: contents, voice_id: "Joanna",})

Save the resulting synthesized speech as an MP3 file.

name = File.basename(filename)parts = name.split('.')first_part = parts[0]mp3_file = first_part + '.mp3'

IO.copy_stream(resp.audio_stream, mp3_file)

86

Page 93: AWS SDK for Ruby › sdk-for-ruby › latest › ...AWS SDK for Ruby to create Ruby applications that use AWS services. This guide contains the following sections: Getting Started

AWS SDK for Ruby Developer GuideAmazon RDS Examples

NoteThe resulting MP3 file is in the MPEG-2 format.

See the complete example on GitHub.

Amazon RDS Examples Using the AWS SDK forRuby

Amazon Relational Database Service (Amazon RDS) is a web service that makes it easier to set up,operate, and scale a relational database in the cloud. You can use the following examples to accessAmazon RDS using the AWS SDK for Ruby. For more information about Amazon RDS, see the AmazonRelational Datbase Service documentation.

NoteSome of the following examples use methods that were introduced in the 2.2.18 version ofthe Aws::RDS::Resource class. To run those examples, you must use that version or a laterversion of the aws-sdk gem.

Topics

• Getting Information about All Amazon RDS Instances (p. 87)

• Getting Information about All Amazon RDS Snapshots (p. 87)

• Getting Information about All Amazon RDS Clusters and Their Snapshots (p. 88)

• Getting Information about All Amazon RDS Security Groups (p. 88)

• Getting Information about All Amazon RDS Subnet Groups (p. 89)

• Getting Information about All Amazon RDS Parameter Groups (p. 89)

• Creating a Snapshot of an Amazon RDS Instance (p. 89)

• Creating a Snapshot of an Amazon RDS Cluster (p. 90)

Getting Information about All Amazon RDS InstancesThe 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' # v2: 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}" putsend

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

87

Page 94: AWS SDK for Ruby › sdk-for-ruby › latest › ...AWS SDK for Ruby to create Ruby applications that use AWS services. This guide contains the following sections: Getting Started

AWS SDK for Ruby Developer GuideGetting Information about All Amazon

RDS Clusters and Their Snapshots

require 'aws-sdk-rds' # v2: 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 Amazon RDS Clustersand Their SnapshotsThe 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' # v2: 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}" endend

Getting Information about All Amazon RDS SecurityGroupsThe following example lists the names of all of your Amazon RDS security groups in the us-west-2region.

NoteAmazon RDS security groups are only applicable when you are using the Amazon EC2-Classicplatform. If you are using Amazon EC2-VPC, use VPC security groups. Both are shown in theexample.

require 'aws-sdk-rds' # v2: 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:'

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:'

88

Page 95: AWS SDK for Ruby › sdk-for-ruby › latest › ...AWS SDK for Ruby to create Ruby applications that use AWS services. This guide contains the following sections: Getting Started

AWS SDK for Ruby Developer GuideGetting Information about All Amazon RDS Subnet Groups

i.vpc_security_groups.each do |vsg| puts vsg.vpc_security_group_id puts ' ' + vsg.status puts endend

Getting Information about All Amazon RDS SubnetGroupsThe 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' # v2: 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_statusend

Getting Information about All Amazon RDSParameter GroupsThe following example lists the names and descriptions of all of your Amazon RDS parameter groups inthe us-west-2 region.

require 'aws-sdk-rds' # v2: 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.descriptionend

Creating a Snapshot of an Amazon RDS InstanceThe following example creates a snapshot for the Amazon RDS instance represented by instance_name inthe us-west-2 region.

NoteIf your instance is a member of a cluster, you can’t create a snapshot of the instance. Instead,you must create a snapshot of the cluster (see Creating a Snapshot of an Amazon RDSCluster (p. 90)).

require 'aws-sdk-rds' # v2: require 'aws-sdk'

rds = Aws::RDS::Resource.new(region: 'us-west-2') instance = rds.db_instance(instance_name) date = Time.newdate_time = date.year.to_s + '-' + date.month.to_s + '-' + date.day.to_s + '-' + date.hour.to_s + '-' + date.min.to_s

89

Page 96: AWS SDK for Ruby › sdk-for-ruby › latest › ...AWS SDK for Ruby to create Ruby applications that use AWS services. This guide contains the following sections: Getting Started

AWS SDK for Ruby Developer GuideCreating a Snapshot of an Amazon RDS Cluster

id = instance_name + '-' + date_time instance.create_snapshot({db_snapshot_identifier: id})

puts "Created snapshot #{id}"

Creating a Snapshot of an Amazon RDS ClusterThe following example creates a snapshot for the Amazon RDS cluster represented by cluster_name inthe us-west-2 region.

require 'aws-sdk-rds' # v2: require 'aws-sdk'

rds = Aws::RDS::Resource.new(region: 'us-west-2') cluster = rds.db_cluster(cluster_name) date = Time.newdate_time = date.year.to_s + '-' + date.month.to_s + '-' + date.day.to_s + '-' + date.hour.to_s + '-' + date.min.to_s

id = cluster_name + '-' + date_time

cluster.create_snapshot({db_cluster_snapshot_identifier: id})

puts "Created cluster snapshot #{id}"

Amazon S3 Examples Using the AWS SDK for RubyAmazon Simple Storage Service (Amazon S3) is storage for the internet. You can use the followingexamples to access Amazon S3 using the AWS SDK for Ruby. Learn more about Amazon S3 at Amazon S3documentation.

Topics

• Getting Information about All Amazon S3 Buckets (p. 91)

• Getting Information about All Amazon S3 Buckets in a Region (p. 91)

• Creating and Using an Amazon S3 Bucket (p. 91)

• Determining Whether an Amazon S3 Bucket Exists (p. 95)

• Getting Information about Amazon S3 Bucket Items (p. 96)

• Uploading an Item to an Amazon S3 Bucket (p. 96)

• Uploading an Item with Metadata to an Amazon S3 Bucket (p. 96)

• Downloading an Object from an Amazon S3 Bucket into a File (p. 97)

• Changing the Properties for an Amazon S3 Bucket Item (p. 97)

• Encrypting Amazon S3 Bucket Items (p. 98)

• Triggering a Notification When an Item is Added to an Amazon S3 Bucket (p. 107)

• Creating a LifeCycle Rule Configuration Template for an Amazon S3 Bucket (p. 108)

• Creating an Amazon S3 Bucket Policy with Ruby (p. 110)

• Configuring an Amazon S3 Bucket for CORS (p. 113)

• Managing Amazon S3 Bucket and Object Access Permissions (p. 116)

90

Page 97: AWS SDK for Ruby › sdk-for-ruby › latest › ...AWS SDK for Ruby to create Ruby applications that use AWS services. This guide contains the following sections: Getting Started

AWS SDK for Ruby Developer GuideGetting Information about All Amazon S3 Buckets

• Using a Amazon S3 Bucket to Host a Website (p. 119)

Getting Information about All Amazon S3 BucketsThe following example lists the names of up to 50 of your Amazon S3 buckets. Copy the code and save itas buckets.rb. Notice that although the Resource object is created in the us-west-2 region, AmazonS3 returns buckets to which you have access, regardless of the region they are in.

require 'aws-sdk-s3' # v2: 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

NoteWhen you specify a region, the buckets method calls the Client#list_buckets method,which returns a list of all buckets owned by the authenticated sender of the request. See GettingInformation about All Amazon S3 Buckets in a Region (p. 91) to learn how to filter this list toget the buckets only in a specific region.

Getting Information about All Amazon S3 Buckets ina RegionThe following example lists the names of the first 50 buckets for the us-west-2 region. If you don’tspecify a limit, Amazon S3 lists all buckets in us-west-2.

require 'aws-sdk-s3' # v2: 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}" endend

NoteIf a bucket is not in the region in which you instantiated your Resource object, the SDK emitsa warning message when you call get_bucket_location. You can suppress this message byredirecting STDERR.On Windows, append 2> nul to the command.On Linux or iOS, append 2> /dev/null to the command.

Creating and Using an Amazon S3 BucketThis 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.

91

Page 98: AWS SDK for Ruby › sdk-for-ruby › latest › ...AWS SDK for Ruby to create Ruby applications that use AWS services. This guide contains the following sections: Getting Started

AWS SDK for Ruby Developer GuideCreating and Using an Amazon S3 Bucket

4. Copy files to the bucket.

5. Delete files from the bucket.

For the complete code for this example, see Complete Example (p. 94).

PrerequisitesTo 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 (p. 4).

2. Set the AWS access credentials that the AWS SDK for Ruby will use to verify your access to AWSservices and resources. For more information, see Configuring the AWS SDK for Ruby (p. 8).

Be sure the AWS credentials map to an AWS Identity and Access Management (IAM) entity with access tothe AWS actions and resources described in this example.

This example assumes you have set the credentials in the AWS credentials profile file and named the filedavid.

Configure the SDKFor this example, add require statements so that you can use the classes and methods provided by theAWS SDK for Ruby for Amazon S3 and work with JSON-formatted data. Then create an Aws::S3::Clientobject in the AWS Region where you want to create the bucket and the specified AWS profile. This codecreates the Aws::S3::Client object in the us-east-1 region. Additional variables are also declaredfor the two buckets used in this example.

require 'aws-sdk-s3' # v2: require 'aws-sdk'require 'json'

profile_name = 'david'region = "us-east-1"bucket = 'doc-sample-bucket'my_bucket = 'david-cloud'

# S3

# Configure SDKs3 = Aws::S3::Client.new(profile: profile_name, region: region)

Get a List of BucketsCall the list_buckets method. This returns an instance of the Aws::S3::Types::ListBucketsOutput class,which represents the list of buckets. Then use the buckets attribute of the ListBucketsOutput classto access the buckets’ properties, such as name for each bucket’s name.

resp = s3.list_bucketsresp.buckets.each do |b| puts b.nameend

Create a BucketCall the create_bucket method, specifying the bucket’s name.

92

Page 99: AWS SDK for Ruby › sdk-for-ruby › latest › ...AWS SDK for Ruby to create Ruby applications that use AWS services. This guide contains the following sections: Getting Started

AWS SDK for Ruby Developer GuideCreating and Using an Amazon S3 Bucket

NoteBucket 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 BucketCall the put_object method, specifying settings such as the bucket’s name and the name of the file tocreate. For the file’s contents, you can specify an instance of a Ruby File class or, in this example, astring representing the file’s data.

To confirm whether the file was uploaded successfully, call the list_objects_v2 method. This returns aninstance of the Aws::S3::Types::ListObjectsV2Output class, which represents the bucket’s objects. Thenuse the contents method of the ListObjectsV2Output class to access the objects’ properties, suchas key for each object’s name.

s3.put_object(bucket: bucket, key: "file1", body: "My first s3 object")

# Check the file existsresp = s3.list_objects_v2(bucket: bucket)resp.contents.each do |obj| puts obj.keyend

Copy Files between BucketsCall 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 objectthat 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 isthe bucket named david-cloud. After the copy operation, test_file in the david-cloud bucket isrenamed file2 in the doc-sample-bucket bucket, and test_file1 in the david-cloud bucket isrenamed 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 BucketCall the delete_objects method. For the delete argument, use an instance of the Aws::S3::Types::Deletetype to represent the objects to delete. In this example, objects represents two files to delete.

To confirm whether the files were deleted successfully, call the list_objects_v2 method as before.This time, when you use the contents method of the class, the deleted file names (represented here bykey) should not be displayed.

s3.delete_objects( bucket: 'doc-sample-bucket', delete: { objects: [ {

93

Page 100: AWS SDK for Ruby › sdk-for-ruby › latest › ...AWS SDK for Ruby to create Ruby applications that use AWS services. This guide contains the following sections: Getting Started

AWS SDK for Ruby Developer GuideCreating and Using an Amazon S3 Bucket

key: 'file2' }, { key: 'file3' } ] })

# Verify objects now have been deletedresp = s3.list_objects_v2(bucket: bucket)resp.contents.each do |obj| puts obj.keyend

Complete ExampleHere is the complete code for this example.

require 'aws-sdk-s3' # v2: require 'aws-sdk'require 'json'

profile_name = 'david'region = "us-east-1"bucket = 'doc-sample-bucket'my_bucket = 'david-cloud'

# S3

# Configure SDKs3 = Aws::S3::Client.new(profile: profile_name, region: region)

# Display a List of Amazon S3 Bucketsresp = s3.list_bucketsresp.buckets.each do |b| puts b.nameend

# Create a S3 bucket from S3::clients3.create_bucket(bucket: bucket)

# Upload a file to s3 bucket, directly putting string datas3.put_object(bucket: bucket, key: "file1", body: "My first s3 object")

# Check the file existsresp = s3.list_objects_v2(bucket: bucket)resp.contents.each do |obj| puts obj.keyend

# Copy files from bucket to buckets3.copy_object(bucket: bucket, copy_source: "#{my_bucket}/test_file", key: 'file2')s3.copy_object(bucket: bucket, copy_source: "#{my_bucket}/test_file1", key: 'file3')

# Delete multiple objects in a single HTTP requests3.delete_objects( bucket: 'doc-sample-bucket', delete: { objects: [ {

94

Page 101: AWS SDK for Ruby › sdk-for-ruby › latest › ...AWS SDK for Ruby to create Ruby applications that use AWS services. This guide contains the following sections: Getting Started

AWS SDK for Ruby Developer GuideDetermining Whether an Amazon S3 Bucket Exists

key: 'file2' }, { key: 'file3' } ] })

# Verify objects now have been deletedresp = s3.list_objects_v2(bucket: bucket)resp.contents.each do |obj| puts obj.keyend

Alternative ApproachesThe following example creates a bucket named my-bucket in the us-west-2 region. This example usesan instance of the Aws::S3::Resource class instead of the Aws::S3::Client class.

require 'aws-sdk-s3' # v2: require 'aws-sdk'

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

Determining Whether an Amazon S3 Bucket ExistsThere are two cases in which you would want to determine whether a bucket already exists. You performthese tests in lieu of receiving an exception if the condition fails:

• You want to determine whether a bucket with a specific name already exists among all buckets, evenones to which you do not have access. This test helps prevent you from trying to create a bucket withthe name of an existing bucket, which causes an exception.

• You want to perform an operation, such as add an item to a bucket, only on a bucket to which youhave access.

The following example sets bucket_exists to true if a bucket with the name my-bucket alreadyexists. The region: parameter to Resource has no effect on the result.

require 'aws-sdk-s3' # v2: 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 andyou have access to the bucket. Again, the region parameter to Client has no effect on the result.

require 'aws-sdk-s3' # v2: require 'aws-sdk'

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

begin client.head_bucket({bucket: 'bucket_name', use_accelerate_endpoint: false}) # We know bucket existsrescue StandardError puts 'Bucket does not exist'end

95

Page 102: AWS SDK for Ruby › sdk-for-ruby › latest › ...AWS SDK for Ruby to create Ruby applications that use AWS services. This guide contains the following sections: Getting Started

AWS SDK for Ruby Developer GuideGetting Information about Amazon S3 Bucket Items

Getting Information about Amazon S3 Bucket ItemsA presigned URL gives you access to the object identified in the URL, if the creator of the presigned URLhas permissions to access that object. You can use a presigned URL to allow a user to click a link and seean item without having to make the item public.

The following example lists the names and presigned URLs of the first 50 items of the bucket my-bucket in the us-west-2 region. If a limit is not specified, Amazon S3 lists up to 1,000 items.

require 'aws-sdk-s3' # v2: require 'aws-sdk'

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

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

# Show only the first 50 itemsbucket.objects.limit(50).each do |item| puts "Name: #{item.key}" puts "URL: #{item.presigned_url(:get)}"end

Uploading an Item to an Amazon S3 BucketThe following example uploads the item (file) C:file.txt to the bucket my-bucket in the us-west-2region. Because C:file.txt is the fully qualified name of the file, the name of the item is set to thename of the file.

require 'aws-sdk-s3' # v2: require 'aws-sdk' s3 = Aws::S3::Resource.new(region: 'us-west-2')

file = 'C:\file.txt'bucket = 'my-bucket' # Get just the file namename = File.basename(file)

# Create the object to uploadobj = s3.bucket(bucket).object(name)

# Upload it obj.upload_file(file)

Uploading an Item with Metadata to an Amazon S3BucketThe following example uploads the item (file) C:file.txt with the metadata key-value pair answerand 42 to the bucket my-bucket in the us-west-2 region. Because C:file.txt is the fully qualifiedname of the file, the name of the item is set to the file name.

require 'aws-sdk-s3' # v2: require 'aws-sdk' s3 = Aws::S3::Resource.new(region: 'us-west-2')

file = 'C:\file.txt'bucket = 'my-bucket'

96

Page 103: AWS SDK for Ruby › sdk-for-ruby › latest › ...AWS SDK for Ruby to create Ruby applications that use AWS services. This guide contains the following sections: Getting Started

AWS SDK for Ruby Developer GuideDownloading an Object from an

Amazon S3 Bucket into a File

# Get just the file namename = File.basename(file)

# Create the object to uploadobj = s3.bucket(bucket).object(name)

# Metadata to addmetadata = {"answer" => "42"}

# Upload it obj.upload_file(file, metadata: metadata)

Downloading an Object from an Amazon S3 Bucketinto a FileThe 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' # v2: require 'aws-sdk'

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

# Create the object to retrieveobj = s3.bucket('my-bucket').object('my-item')

# Get the item's content and save it to a fileobj.get(response_target: './my-code/my-item.txt')

Changing the Properties for an Amazon S3 BucketItemThe following example adds public read-only access, sets server-side encryption to AES-256, and sets thestorage class to Reduced Redundancy for the item my-item in the bucket my-bucket in the us-west-2region.

require 'aws-sdk-s3' # v2: require 'aws-sdk'

args_list = {}args_list[:bucket] = 'my-bucket'args_list[:key] = 'my-item'

# Where we are getting the source to copy fromargs_list[:copy_source] = 'my-bucket/my-item'

# The acl can be any of:# private, public-read, public-read-write, authenticated-read, aws-exec-read, bucket-owner-read, bucket-owner-full-controlargs_list[:acl] = 'public-read'

# The encryption can be any of:# AES256, aws:kmsargs_list[:server_side_encryption] = 'AES256'

# The storage_class can be any of:# STANDARD, REDUCED_REDUNDANCY, STANDARD_IAargs_list[:storage_class] = 'REDUCED_REDUNDANCY'

97

Page 104: AWS SDK for Ruby › sdk-for-ruby › latest › ...AWS SDK for Ruby to create Ruby applications that use AWS services. This guide contains the following sections: Getting Started

AWS SDK for Ruby Developer GuideEncrypting Amazon S3 Bucket Items

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

client.copy_object(args_list)

Encrypting Amazon S3 Bucket ItemsAmazon S3 supports encrypting Amazon S3 bucket objects on both the client and the server. To encryptobjects on the client, you perform the encryption yourself, either using keys that you create or keys thatAWS Key Management Service (AWS KMS) manages for you.

To encrypt objects on the server, you have more options.

• You can have Amazon S3 automatically encrypt objects as you upload them to a bucket. Once youconfigure a bucket with this option, every object that you upload–from that point on–is encrypted.

• You can have Amazon S3 encrypt an object when you upload it to a bucket. The disadvantage with thisapproach is that you can still upload objects that are not encrypted.

• You can have Amazon S3 encrypt an object when you upload it to a bucket. The disadvantage with thisapproach is that you can still upload objects that are not encrypted.

The following examples describe these options, from the simplest example of specifying that all objectsuploaded to a bucket are automatically encrypted, to the most complex example of using asymmetricpublic and private keys on the client. Don’t worry, we’ll explain these concepts as we go. Learn aboutencryption in Amazon S3 at Protecting Data Using Encryption.

Topics• Server-Side Encryption (p. 98)• Client-Side Encryption (p. 102)

Server-Side EncryptionTo encrypt objects on the server, you have the following options.

• You can have Amazon S3 automatically encrypt objects as you upload them to a bucket. Once youconfigure a bucket with this option, every object that you upload–from that point on–is encrypted.

• You can have Amazon S3 encrypt an object when you upload it to a bucket. The disadvantage with thisapproach is that you can still upload objects that are not encrypted.

• You can have Amazon S3 reject objects that are not encrypted when you attempt to upload them to abucket.

Learn about service-side encryption in Amazon S3 at Protecting Data Using Server-Side Encryption.

Topics• Setting Default Server-Side Encryption for an Amazon S3 Bucket (p. 98)• Encrypting an Amazon S3 Bucket Object on the Server (p. 99)• Requiring Encryption on the Server to Upload Amazon S3 Bucket Objects (p. 100)• Encrypting an Amazon S3 Bucket Object with an AWS KMS Key (p. 101)

Setting Default Server-Side Encryption for an Amazon S3 Bucket

The following example uses the put_bucket_encryption method to enable KMS server-side encryption onany items added to my_bucket in the us-west-2 region.

98

Page 105: AWS SDK for Ruby › sdk-for-ruby › latest › ...AWS SDK for Ruby to create Ruby applications that use AWS services. This guide contains the following sections: Getting Started

AWS SDK for Ruby Developer GuideEncrypting Amazon S3 Bucket Items

The only exception is if the user configures their request to explicitly use server-side encryption. In thatcase, the specified encryption takes precedence.

Choose Copy to save the code locally.

Create the file add_default_sse_encryption.rb.

Add the required Amazon S3 gem.

NoteVersion 2 of the AWS SDK for Ruby didn’t have service-specific gems.

require 'aws-sdk-s3' # In v2: require 'aws-sdk'

Get the KMS key from the command line, Where key is a KMS key ID as created in the Creating a CMK inAWS KMS (p. 79) example.

if ARGV.empty?() puts 'You must supply a key' exit 1end

key = ARGV[0]

Create an Amazon S3 client and call put_bucket_encryption to add default encryption to the bucket.

client.put_bucket_encryption( bucket: 'my_bucket', server_side_encryption_configuration: { rules: [{ apply_server_side_encryption_by_default: { sse_algorithm: 'aws:kms', kms_master_key_id: key } }] })

See the complete example on GitHub.

Encrypting an Amazon S3 Bucket Object on the Server

The following example uses the put_object method to add the object my_item to the bucketmy_bucket in the us-west-2 region with server-side encryption set KMS.

Note that this differs from Setting Default Server-Side Encryption for an Amazon S3 Bucket (p. 98), isin that case, the objects are encrypted without you having to explicitly perform the operation.

Choose Copy to save the code locally.

Create the file encrypt_object_sse.rb.

Add the required Amazon S3 gem.

NoteVersion 2 of the AWS SDK for Ruby didn’t have service-specific gems.

require 'aws-sdk-s3' # In v2: require 'aws-sdk'

99

Page 106: AWS SDK for Ruby › sdk-for-ruby › latest › ...AWS SDK for Ruby to create Ruby applications that use AWS services. This guide contains the following sections: Getting Started

AWS SDK for Ruby Developer GuideEncrypting Amazon S3 Bucket Items

Set the bucket and object name and get the object from the file as a string.

bucket = 'my_bucket'item = 'my_item'contents = File.read(item)

Create an Amazon S3 client and call put_object to upload the object to the bucket. Notice that theserver_side_encryption property is set to aws:kms, indicating that Amazon S3 encrypts the objectusing KMS. Finally, display a success message to the user.

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

client.put_object( body: contents, bucket: bucket, key: item, server_side_encryption: 'aws:kms')

puts 'Added item ' + name + ' to bucket ' + bucket

See the complete example on GitHub.

Requiring Encryption on the Server to Upload Amazon S3 Bucket Objects

The following example uses the put_bucket_policy method to require that objects uploaded to anAmazon S3 bucket have Amazon S3 encrypt the object with an AWS KMS key. Attempts to uploadan object without specifying that Amazon S3 encrypt the object with an AWS KMS key raise anAws::S3::Errors::AccessDenied exception.

Avoid using this configuration option if you use default server-side encryption as described in SettingDefault Server-Side Encryption for an Amazon S3 Bucket (p. 98) as they could conflict and result inunexpected results.

Choose Copy to save the code locally.

Create the file add_sses3_policy.rb.

Add the required Amazon S3 gem and set the bucket name.

NoteVersion 2 of the AWS SDK for Ruby didn’t have service-specific gems.

require 'aws-sdk-s3' # In v2: require 'aws-sdk'bucket = 'my_bucket'

Create an Amazon S3 policy that requires server-side KMS encryption on objects uploaded to the bucket.

policy = { 'Version': '2012-10-17', 'Id': 'PutObjPolicy', 'Statement': [ { 'Sid': 'DenyIncorrectEncryptionHeader', 'Effect': 'Deny', 'Principal': '*', 'Action': 's3:PutObject', 'Resource': 'arn:aws:s3:::' + bucket + '/*', 'Condition': {

100

Page 107: AWS SDK for Ruby › sdk-for-ruby › latest › ...AWS SDK for Ruby to create Ruby applications that use AWS services. This guide contains the following sections: Getting Started

AWS SDK for Ruby Developer GuideEncrypting Amazon S3 Bucket Items

'StringNotEquals': { 's3:x-amz-server-side-encryption': 'aws:kms' } } }, { 'Sid': 'DenyUnEncryptedObjectUploads', 'Effect': 'Deny', 'Principal': '*', 'Action': 's3:PutObject', 'Resource': 'arn:aws:s3:::' + bucket + '/*', 'Condition': { 'Null': { 's3:x-amz-server-side-encryption': 'true' } } } ]}.to_json

Create the Amazon S3 client, apply the policy to the bucket, and print a success message.

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

# Apply bucket policys3.put_bucket_policy( bucket: bucket, policy: policy)

puts 'Successfully added policy to bucket ' + bucket

See the complete example on GitHub.

Encrypting an Amazon S3 Bucket Object with an AWS KMS Key

The following example uses the put_object method to add the object my_item to the bucketmy_bucket in the us-west-2 region with server-side AWS KMS encryption where you provide the key.See Creating a CMK in AWS KMS (p. 79) for information on creating an AWS KMS key.

Amazon S3 uses, but does not store, the AWS KMS key that you provide.

Choose Copy to save the code locally.

Create the file encrypt_object_sseck.rb.

Add the required Amazon S3 and md5 gems.

NoteVersion 2 of the AWS SDK for Ruby didn’t have service-specific gems.

require 'aws-sdk-s3' # In v2: require 'aws-sdk'require 'digest/md5'

Get the key from the command-line. If there is no command-line argument, print an error message andquit. Otherwise, create an MD5 hash of the key. Amazon S3 uses the hash to ensure the integrity of thekey.

if ARGV.empty?() puts 'You must supply the key'

101

Page 108: AWS SDK for Ruby › sdk-for-ruby › latest › ...AWS SDK for Ruby to create Ruby applications that use AWS services. This guide contains the following sections: Getting Started

AWS SDK for Ruby Developer GuideEncrypting Amazon S3 Bucket Items

exit 1end

key = ARGV[0] # KMS key is a stringmd5 = Digest::MD5.digest(key)

Set the bucket and object names, and get the contents of the object from the file as a string.

bucket = 'my_bucket'item = 'my_item'contents = File.read(item)

Create an Amazon S3 client and call put_object to upload the object to the bucket. Notice that theserver_side_encryption property is set to aws:kms, indicating that Amazon S3 encrypts the objectusing the provided AWS KMS key. Finally, display a success message to the user.

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

# Encrypt item with user-supplied KMS key on serverclient.put_object( body: contents, bucket: bucket, key: item, sse_customer_algorithm: 'aws:kms', sse_customer_key: key, sse_customer_key_md5: md5)

puts 'Added item ' + item + ' to bucket ' + bucket

See the complete example on GitHub.

Client-Side EncryptionTo encrypt objects on the client, you perform the encryption yourself, either using keys that you createor keys that AWS Key Management Service (AWS KMS) manages for you.

Learn about client-side encryption in Amazon S3 at Protecting Data Using Client-Side Encryption.

Topics• Encrypting an Amazon S3 Bucket Object with an AWS KMS Key (p. 102)• Decrypting an Amazon S3 Bucket Object with an AWS KMS Key (p. 103)• Creating Public and Private Asymmetric Keys (p. 104)• Encrypting an Amazon S3 Bucket Object with a Public Key (p. 105)• Decrypting an Amazon S3 Bucket Object with a Private Key (p. 106)

Encrypting an Amazon S3 Bucket Object with an AWS KMS Key

The following example uses the put_object method to add the object my_item to the bucketmy_bucket in the us-west-2 region.

Choose Copy to save the code locally.

Create the file encrypt_object_csekms.rb.

Add the required Amazon S3 gem.

102

Page 109: AWS SDK for Ruby › sdk-for-ruby › latest › ...AWS SDK for Ruby to create Ruby applications that use AWS services. This guide contains the following sections: Getting Started

AWS SDK for Ruby Developer GuideEncrypting Amazon S3 Bucket Items

NoteVersion 2 of the AWS SDK for Ruby didn’t have service-specific gems.

require 'aws-sdk-s3' # In v2: require 'aws-sdk'

Get the AWS KMS key from the command line, where key is an AWS KMS key ID as created in theCreating a CMK in AWS KMS (p. 79) example.

if ARGV.empty?() puts 'You must supply a key' exit 1end

key = ARGV[0]

Set the bucket and object name and get the contents of the object from the file as a string.

bucket = 'my_bucket'item = 'my_item'contents = File.read(item)

Create a AWS KMS and Amazon S3 encryption client, call put_object to upload the object to thebucket, and display a success message.

kms = Aws::KMS::Client.new

# Create encryption clientclient = Aws::S3::Encryption::Client.new( kms_key_id: key, kms_client: kms)

# Add encrypted item to bucketclient.put_object( body: contents, bucket: bucket, key: item)

puts 'Added client-side KMS encrypted item ' + item + ' to bucket ' + bucket

See the complete example on GitHub.

Decrypting an Amazon S3 Bucket Object with an AWS KMS Key

The following example uses the get_object method to get the object my_item from the bucketmy_bucket in the us-west-2 region.

Choose Copy to save the code locally.

Create the file decrypt_object_csekms.rb.

Add the required Amazon S3 gem.

NoteVersion 2 of the AWS SDK for Ruby didn’t have service-specific gems.

require 'aws-sdk-s3' # In v2: require 'aws-sdk'

103

Page 110: AWS SDK for Ruby › sdk-for-ruby › latest › ...AWS SDK for Ruby to create Ruby applications that use AWS services. This guide contains the following sections: Getting Started

AWS SDK for Ruby Developer GuideEncrypting Amazon S3 Bucket Items

Get the AWS KMS key from the command line, Where key is an AWS KMS key ID as created in theCreating a CMK in AWS KMS (p. 79) example and must be the same value you used to encrypt theobject.

if ARGV.empty?() puts 'You must supply a key' exit 1end

key = ARGV[0]

Set the bucket name and object name.

bucket = 'my_bucket'item = 'my_item'

Create a AWS KMS and Amazon S3 client.

kms = Aws::KMS::Client.newclient = Aws::S3::Encryption::Client.new( kms_key_id: key, kms_client: kms,)

Call get_object to get the object and display the result.

resp = client.get_object(bucket: bucket, key: item)puts resp.body.read

See the complete example on GitHub.

Creating Public and Private Asymmetric Keys

The following example uses the PKey class to create a public and private keys. Use the public key toencrypt objects on the client before you upload them to an Amazon S3 bucket. Use the private key andpass phrase to decrypt objects on the client after you download them from an Amazon S3 bucket. TheEncrypting an Amazon S3 Bucket Object with a Public Key (p. 105) and Decrypting an Amazon S3Bucket Object with a Private Key (p. 106) examples use public and private keys, respectively.

Choose Copy to save the code locally.

Create the file create_rsa_keys.rb.

Add the required OpenSSL gem.

require 'openssl'

Get the pass phrase, which is used to seed and create the key, from the command line.

if ARGV.empty?() puts 'You must supply a pass phrase' exit 1end

pass_phrase = ARGV[0]

104

Page 111: AWS SDK for Ruby › sdk-for-ruby › latest › ...AWS SDK for Ruby to create Ruby applications that use AWS services. This guide contains the following sections: Getting Started

AWS SDK for Ruby Developer GuideEncrypting Amazon S3 Bucket Items

Create the RSA key pairs. Save the public key as public_key.pem and the private key asprivate_secure_key.pem.

key = OpenSSL::PKey::RSA.new 2048

# Files to store public and private keyspublic_key_file = 'public_key.pem'private_key_file = 'private_secure_key.pem'

open public_key_file, 'w' do |io| io.write key.public_key.to_pemend

cipher = OpenSSL::Cipher.new 'AES-128-CBC'key_secure = key.export cipher, pass_phrase

open private_key_file, 'w' do |io| io.write key_secureend

Display the names of the key files and the pass phrase.

puts 'The public key is in ' + public_key_fileputs 'The private key is in ' + private_key_file + ' using the pass phrase:'puts '"' + pass_phrase + '"'

See the complete example on GitHub.

Encrypting an Amazon S3 Bucket Object with a Public Key

The following example uses the PKey class to encrypt an object with a public key and the put_objectmethod to add the object my_item to the bucket my_bucket in the us-west-2 region.

Choose Copy to save the code locally.

Create the file encrypt_object_csepk.rb.

Add the required Amazon S3 and OpenSSL gems.

NoteVersion 2 of the AWS SDK for Ruby didn’t have service-specific gems.

require 'aws-sdk-s3' # v2: require 'aws-sdk'require 'openssl'

Set the bucket name, object name, and name of the file containing the public key. See Creating Publicand Private Asymmetric Keys (p. 104) for information about creating a public key.

bucket = 'my_bucket'item = 'my_item'key_file = 'public_key.pem'

Get the file contents as a string; get the public key from the file and create a new RSA key to encrypt thebucket object.

contents = File.read(item)public_key = File.read(key_file)key = OpenSSL::PKey::RSA.new(public_key)

105

Page 112: AWS SDK for Ruby › sdk-for-ruby › latest › ...AWS SDK for Ruby to create Ruby applications that use AWS services. This guide contains the following sections: Getting Started

AWS SDK for Ruby Developer GuideEncrypting Amazon S3 Bucket Items

Create an Amazon S3 encryption client and call put_object to upload the object to the bucket. Finally,display a message to the user about the results.

enc_client = Aws::S3::Encryption::Client.new(encryption_key: key)

# Add encrypted item to bucket enc_client.put_object( body: contents, bucket: bucket, key: item_name )

puts 'Added ' + item_name + ' to bucket ' + bucket + ' using key from ' + key_file

See the complete example on GitHub.

Decrypting an Amazon S3 Bucket Object with a Private Key

The following example uses the get_object method to get the object my_item from the bucketmy_bucket in the us-west-2 region. Then it decrypts the contents with the PKey class.

Choose Copy to save the code locally.

Create the file decrypt_object_csepk.rb.

Add the required Amazon S3 and OpenSSL gems.

NoteVersion 2 of the AWS SDK for Ruby didn’t have service-specific gems.

require 'aws-sdk-s3' # v2: require 'aws-sdk'require 'openssl'

Get the pass phrase from the command line.

if ARGV.empty?() puts 'You must supply a pass phrase' exit 1end

pass_phrase = ARGV[0]

Set the bucket name, object name, and name of the private key file.

bucket = 'my_bucket'item = 'my_item'key_file = 'private_key.pem'

Create an RSA key from the contents of the key file and passphrase.

private_key = File.binread(key_file)key = OpenSSL::PKey::RSA.new(private_key, pass_phrase)

Create an Amazon S3 encryption client, call get_object, get the contents of the object as text andprint out the object’s contents.

enc_client = Aws::S3::Encryption::Client.new(encryption_key: key)

106

Page 113: AWS SDK for Ruby › sdk-for-ruby › latest › ...AWS SDK for Ruby to create Ruby applications that use AWS services. This guide contains the following sections: Getting Started

AWS SDK for Ruby Developer GuideTriggering a Notification When an

Item is Added to an Amazon S3 Bucket

resp = enc_client.get_object(bucket: bucket, key: item)puts resp.body.read

See the complete example on GitHub.

Triggering a Notification When an Item is Added toan Amazon S3 BucketYou 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 AWS Lambda function

To create a bucket notification, use the following procedure.

1. Grant Amazon S3 permission to publish an item to a queue or topic, or invoke a Lambdafunction (p. 107).

2. Set the bucket’s Notification Configuration to point to the queue, topic, or function (p. 107).

After you do these steps, your application can respond to the information. For example, the Lambdatopic Programming Model describes how to use the various programming languages that Lambdasupports.

Enabling Amazon S3 to Send a NotificationLearn how to configure an Amazon SNS topic or Amazon SQS queue, or create a Lambda function so thatAmazon S3 can send a notification to them.

• Enabling a Resource to Publish to an Amazon SNS Topic (p. 127)• Enabling a Resource to Publish to a Queue in Amazon SQS (p. 137)• Configuring a Lambda Function to Receive Notifications (p. 84)

Creating an Amazon S3 Bucket NotificationThis example enables the Amazon S3 bucket my-bucket to send a notification to the following when anitem 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-s3' # v2: require 'aws-sdk'

107

Page 114: AWS SDK for Ruby › sdk-for-ruby › latest › ...AWS SDK for Ruby to create Ruby applications that use AWS services. This guide contains the following sections: Getting Started

AWS SDK for Ruby Developer GuideCreating a LifeCycle Rule Configuration

Template for an Amazon S3 Bucket

req = {}req[:bucket] = bucket_name

events = ['s3:ObjectCreated:*']

notification_configuration = {}

# Add functionlc = {}

lc[:lambda_function_arn] = 'my-function-arn'lc[:events] = eventslambda_configurations = []lambda_configurations << lc

notification_configuration[:lambda_function_configurations] = lambda_configurations

# Add queueqc = {}

qc[:queue_arn] = 'my-topic-arn'qc[:events] = eventsqueue_configurations = []queue_configurations << qc

notification_configuration[:queue_configurations] = queue_configurations

# Add topictc = {}

tc[:topic_arn] = 'my-topic-arn'tc[:events] = eventstopic_configurations = []topic_configurations << tc

notification_configuration[:topic_configurations] = topic_configurations

req[:notification_configuration] = notification_configuration

req[:use_accelerate_endpoint] = false

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

s3.put_bucket_notification_configuration(req)

Creating a LifeCycle Rule Configuration Template foran Amazon S3 BucketIf you have (or plan to create) a non-trivial number of objects and want to specify when to move them tolong-term storage or delete them, you can save a lot of time by creating a template for the lifecycle rulesand applying that template to all of your Amazon S3 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:

108

Page 115: AWS SDK for Ruby › sdk-for-ruby › latest › ...AWS SDK for Ruby to create Ruby applications that use AWS services. This guide contains the following sections: Getting Started

AWS SDK for Ruby Developer GuideCreating a LifeCycle Rule Configuration

Template for an Amazon S3 Bucket

Run the following code to produce a JSON representation of that rule. Save the output asdefault.json.

require 'aws-sdk'

s3 = Aws::S3::Client.new(region: 'us-west-2')resp = s3.get_bucket_lifecycle_configuration(bucket: 'default')

resp.rules.each do |rule| rule.to_hash.to_jsonend

The output should look like the following.

[{"expiration":{"date":null,"days":425},"id":"default","prefix":"","status":"Enabled","transitions":[{"date":null,"days":30,"storage_class":"STANDARD_IA"},{"date":null,"days":60,"storage_class":"GLACIER"}],"noncurrent_version_transitions":[],"noncurrent_version_expiration":null}]

Now that you have the JSON for a lifecycle rule, you can apply it to any other bucket using the followingexample. The example 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] }

109

Page 116: AWS SDK for Ruby › sdk-for-ruby › latest › ...AWS SDK for Ruby to create Ruby applications that use AWS services. This guide contains the following sections: Getting Started

AWS SDK for Ruby Developer GuideCreating an Amazon S3 Bucket Policy with Ruby

map end

def to_json(*a) to_map.to_json(*a) endend

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) endend

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) endend

# Pull in contents as a stringvalue = File.open('default.json', "rb").readjson_data = JSON.parse(value, opts={symbolize_names: true})

s3 = Aws::S3::Client.new(region: 'us-west-2')s3.put_bucket_lifecycle_configuration(:bucket => 'other_bucket', :lifecycle_configuration => {:rules => json_data})

NoteBest PracticeWe recommend that you enable the AbortIncompleteMultipartUpload lifecycle rule on yourAmazon S3 buckets.This rule directs Amazon S3 to abort multipart uploads that don’t complete within a specifiednumber of days after being initiated. When the set time limit is exceeded, Amazon S3 aborts theupload and then deletes the incomplete upload data.For more information, see Lifecycle Configuration for a Bucket with Versioning in the AmazonS3 User Guide.

Creating an Amazon S3 Bucket Policy with RubyThis 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.

110

Page 117: AWS SDK for Ruby › sdk-for-ruby › latest › ...AWS SDK for Ruby to create Ruby applications that use AWS services. This guide contains the following sections: Getting Started

AWS SDK for Ruby Developer GuideCreating an Amazon S3 Bucket Policy with Ruby

For the complete code for this example, see Complete Example (p. 112).

PrerequisitesTo 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 (p. 4).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 (p. 8).

Be sure the AWS credentials map to an AWS Identity and Access Management (IAM) entity with access tothe AWS actions and resources described in this example.

This example assumes you have set the credentials in the AWS credentials profile file or in theAWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY environment variables on your local system.

Configure the SDKTo configure the SDK for this example, add a require statement so you can use the classes andmethods provided by the AWS SDK for Ruby for Amazon S3. Then create an Aws::S3::Client object in theAWS Region where you want to create the bucket. This code creates the Aws::S3::Client object in theus-west-2 region.

require 'aws-sdk-s3' # v2: require 'aws-sdk'

s3 = Aws::S3::Client.new(region: "us-west-2")

Create a BucketCall the create_bucket method, specifying the bucket’s name. This code uses a variable named bucketto represent the bucket’s name. Substitute example-bucket-name for your bucket’s name.

NoteBucket 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 PolicyDeclare a Ruby hash that represents the policy. Then call the to_json method on the hash to convertit to a JSON object. This code uses a variable named policy that contains the policy definition. Thispolicy 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 ResourceName (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"

111

Page 118: AWS SDK for Ruby › sdk-for-ruby › latest › ...AWS SDK for Ruby to create Ruby applications that use AWS services. This guide contains the following sections: Getting Started

AWS SDK for Ruby Developer GuideCreating an Amazon S3 Bucket Policy with Ruby

] }, "Action" => "s3:*", "Resource" => [ "arn:aws:s3:::#{bucket}" ] } ]}.to_json

For examples of the types of policies you can define, see Bucket Policy Examples in the Amazon S3Developer Guide.

Add the Policy to the BucketCall 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 PolicyYou can call the put_bucket_policy method again with a complete replacement policy. However,you can also make incremental updates to an existing policy, which can reduce the amount of code youneed to write. To do this, retrieve the current policy by calling the get_bucket_policy method. Next,parse the JSON object that is returned into a Ruby hash. Then make your incremental changes to thepolicy. For example, this code changes the ARN of the IAM entity. After you make your changes, call theput_bucket_policy method again. Be sure to call the to_json method on the hash to convert it backto a JSON object before applying the changed policy to the bucket.

policy_string = s3.get_bucket_policy(bucket: bucket).policy.readpolicy_json = JSON.parse(policy_string)

policy_json["Statement"][0]["Principal"]["AWS"] = "arn:aws:iam::111122223333:root"

s3.put_bucket_policy( bucket: bucket, policy: policy_json.to_json)

Clean UpTo remove the policy from the bucket, call the delete_bucket_policy method, specifying the name of thebucket.

To delete the bucket, call the delete_bucket method, specifying the name of the bucket.

s3.delete_bucket_policy(bucket: bucket)s3.delete_bucket(bucket: bucket)

Complete ExampleHere is the complete code for this example.

require 'aws-sdk-s3' # v2: require 'aws-sdk'

112

Page 119: AWS SDK for Ruby › sdk-for-ruby › latest › ...AWS SDK for Ruby to create Ruby applications that use AWS services. This guide contains the following sections: Getting Started

AWS SDK for Ruby Developer GuideConfiguring an Amazon S3 Bucket for CORS

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.readpolicy_json = JSON.parse(policy_string)

policy_json["Statement"][0]["Principal"]["AWS"] = "arn:aws:iam::111122223333:root"

s3.put_bucket_policy( bucket: bucket, policy: policy_json.to_json)

s3.delete_bucket_policy(bucket: bucket)s3.delete_bucket(bucket: bucket)

Configuring an Amazon S3 Bucket for CORSThis example demonstrates how to use the AWS SDK for Ruby to:

1. Configure Cross-Origin Resource Sharing (CORS) settings for an Amazon S3 bucket.2. Get the CORS settings for a bucket.

For more information about CORS support in Amazon S3, see Cross-Origin Resource Sharing (CORS) inthe Amazon S3 Developer Guide.

For the complete code for this example, see Complete Example (p. 115).

PrerequisitesTo 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 (p. 4).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 (p. 8).

113

Page 120: AWS SDK for Ruby › sdk-for-ruby › latest › ...AWS SDK for Ruby to create Ruby applications that use AWS services. This guide contains the following sections: Getting Started

AWS SDK for Ruby Developer GuideConfiguring an Amazon S3 Bucket for CORS

3. Create an Amazon S3 bucket or identify an existing bucket in your AWS account.

Be sure the AWS credentials map to an AWS Identity and Access Management (IAM) entity with access tothe AWS actions and resources described in this example.

This example assumes:

• 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 SDKFor this example, add a require statement so that you can use the classes and methods provided by theAWS SDK for Ruby for Amazon S3. Then create an Aws::S3::Client object in the AWS Region where youwant to create the bucket and the specified AWS profile. This code creates the Aws::S3::Client objectin the us-east-1 region. An additional variable is also declared for the bucket used in this example.

require 'aws-sdk-s3' # v2: require 'aws-sdk'

profile_name = 'david'region = 'us-east-1'bucket = 'doc-sample-bucket'

# S3 - Configuring an S3 Bucket

# Create a S3 clients3 = Aws::S3::Client.new(profile: profile_name, region:region)

Configure CORS for a BucketCall the put_bucket_cors method, providing the name of the bucket and the CORS configurationsettings.

s3.put_bucket_cors( bucket: bucket, cors_configuration: cors_configuration)

For the CORS configuration settings, declare an Aws::S3::Types::CORSConfiguration hash. Specify thingssuch as the HTTP methods that the specified origins are allowed to execute (allowed_methods), theorigins you want customers to be able to access the bucket from (allowed_origins), and the headersin the response you want customers to be able to access from their applications (for example, from aJavaScript XMLHttpRequest object, shown here in expose_headers).

cors_configuration = { cors_rules: [ { allowed_methods: allowed_methods, allowed_origins: ["*"], expose_headers: ["ExposeHeader"], }, ]}

For the HTTP methods that the specified origins are allowed to execute, you could specify them inline or,as shown here, you could get them from the user at the command line.

114

Page 121: AWS SDK for Ruby › sdk-for-ruby › latest › ...AWS SDK for Ruby to create Ruby applications that use AWS services. This guide contains the following sections: Getting Started

AWS SDK for Ruby Developer GuideConfiguring an Amazon S3 Bucket for CORS

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" endend

For example, assuming the code file is named doc_sample_code_s3_bucket_cors.rb, and you wantto allow the specified origins to execute only GET and POST methods, here is how the user could run thecode from the command line.

ruby doc_sample_code_s3_bucket_cors.rb get post

Get the CORS Settings for a BucketCall the get_bucket_cors method, providing the name of the bucket. The get_bucket_cors methodreturns an Aws::S3::Types::GetBucketCorsOutput object. This object’s cors_rules attribute returns anarray of Aws::S3::Types::CORSRule objects, which represent the bucket’s CORS settings.

resp = s3.get_bucket_cors(bucket: bucket)puts resp.cors_rules

Complete ExampleHere is the complete code for this example.

require 'aws-sdk-s3' # v2: require 'aws-sdk'

profile_name = 'david'region = 'us-east-1'bucket = 'doc-sample-bucket'

# S3 - Configuring an S3 Bucket

# Create a S3 clients3 = Aws::S3::Client.new(profile: profile_name, region:region)

# Setting a Bucket CORS Configuration

# Create array of allowed methods parameter based on command line parametersallowed_methods = []ARGV.each do |arg| case arg.upcase when "POST" allowed_methods << "POST" when "GET"

115

Page 122: AWS SDK for Ruby › sdk-for-ruby › latest › ...AWS SDK for Ruby to create Ruby applications that use AWS services. This guide contains the following sections: Getting Started

AWS SDK for Ruby Developer GuideManaging Amazon S3 Bucket

and Object Access Permissions

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" endend

# Create CORS configuration hashcors_configuration = { cors_rules: [ { allowed_methods: allowed_methods, allowed_origins: ["*"], expose_headers: ["ExposeHeader"], }, ]}

# Set the new CORS configuration on the selected buckets3.put_bucket_cors( bucket: bucket, cors_configuration: cors_configuration)

# Retrieving a Bucket CORS Configurationresp = s3.get_bucket_cors(bucket: bucket)puts resp.cors_rules

# To run the example, type the following at the command line including one or more HTTP methods as shown# ruby doc_sample_code_s3_bucket_cors.rb get post

Managing Amazon S3 Bucket and Object AccessPermissionsThis 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 (p. 118).

PrerequisitesTo 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 (p. 4).

2. Set the AWS access credentials that the AWS SDK for Ruby will use to verify your access to AWSservices and resources. For more information, see Configuring the AWS SDK for Ruby (p. 8).

116

Page 123: AWS SDK for Ruby › sdk-for-ruby › latest › ...AWS SDK for Ruby to create Ruby applications that use AWS services. This guide contains the following sections: Getting Started

AWS SDK for Ruby Developer GuideManaging Amazon S3 Bucket

and Object Access Permissions

Be sure the AWS credentials map to an AWS Identity and Access Management (IAM) entity with access tothe AWS actions and resources described in this example.

This example assumes you have set the credentials in the AWS credentials profile file or in theAWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY environment variables on your local system.

Configure the SDKFor this example, add a require statement so that you can use the classes and methods provided by theAWS SDK for Ruby for Amazon S3. Then create an Aws::S3::Client object in the AWS Region where youwant to create the bucket. This code creates the Aws::S3::Client object in the us-west-2 region.This code also declares a variable representing the bucket.

require 'aws-sdk-s3' # v2: require 'aws-sdk'

# Create a S3 clientclient = Aws::S3::Client.new(region: 'us-west-2')

Set a Canned ACL for a BucketCall the put_bucket_acl method, specifying the names of the canned ACL and the bucket. This code setsthe public-read canned ACL on the bucket, which enables full control for the bucket’s owner 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 theAmazon 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 BucketCall the put_object method, specifying the names of the bucket and object and the object’s content. Thiscode declares a variable representing the object.

object_key = "my-key"# Put an object in the public bucketclient.put_object({ bucket: bucket, key: object_key, body: 'Hello World',})

Set a Canned ACL for an ObjectBy default, you can’t get the contents of the object in the bucket. To confirm this behavior, call the RubyNet::HTTP.get method to attempt to get the object’s content.

object_path = "http://#{bucket}.s3-us-west-2.amazonaws.com/#{object_key}"

117

Page 124: AWS SDK for Ruby › sdk-for-ruby › latest › ...AWS SDK for Ruby to create Ruby applications that use AWS services. This guide contains the following sections: Getting Started

AWS SDK for Ruby Developer GuideManaging Amazon S3 Bucket

and Object Access Permissions

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 fullcontrol for the object’s owner and read-only access for everyone else. After the call, try to get theobject’s content again.

client.put_object_acl({ acl: "public-read", bucket: bucket, key: object_key,})object_path = "http://#{bucket}.s3-us-west-2.amazonaws.com/#{object_key}"puts "Now I can access object (#{object_key}) :\n#{Net::HTTP.get(URI(object_path))}\n\n"

Get a Bucket’s Current ACLCall the get_bucket_acl method, specifying the name of the bucket. The get_bucket_acl methodreturns an instance of the Aws::S3::Types::GetBucketAclOutput class. Use the grants attribute of theGetBucketAclOutput class to list the bucket’s current ACL.

resp = client.get_bucket_acl(bucket: bucket)puts resp.grants

Complete ExampleHere is the complete code for this example.

require 'aws-sdk-s3' # v2: require 'aws-sdk'

# Create a S3 clientclient = Aws::S3::Client.new(region: 'us-west-2')

bucket = 'my-bucket'# Sets a bucket to public-readclient.put_bucket_acl({ acl: "public-read", bucket: bucket,})

object_key = "my-key"# Put an object in the public bucketclient.put_object({ bucket: bucket, key: object_key, body: 'Hello World',})

# Accessing an object in the bucket with unauthorize requestbucket_path = "http://#{bucket}.s3-us-west-2.amazonaws.com/"resp = Net::HTTP.get(URI(bucket_path))puts "Content of unsigned request to #{bucket_path}:\n\n#{resp}\n\n"

# However, accessing the object is denied since object Acl is not public-readobject_path = "http://#{bucket}.s3-us-west-2.amazonaws.com/#{object_key}"resp = Net::HTTP.get(URI(object_path))puts "Content of unsigned request to #{object_path}:\n\n#{resp}\n\n"

# Setting the object to public-read

118

Page 125: AWS SDK for Ruby › sdk-for-ruby › latest › ...AWS SDK for Ruby to create Ruby applications that use AWS services. This guide contains the following sections: Getting Started

AWS SDK for Ruby Developer GuideUsing a Amazon S3 Bucket to Host a Website

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 againclient.put_bucket_acl({ bucket: bucket, acl: 'private',})

# Get current bucket Aclresp = client.get_bucket_acl(bucket: bucket)puts resp.grants

resp = Net::HTTP.get(URI(bucket_path))puts "Content of unsigned request to #{bucket_path}:\n\n#{resp}\n\n"

Using a Amazon S3 Bucket to Host a WebsiteThis 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 theAmazon S3 Developer Guide.

For the complete code for this example, see Complete Example (p. 121).

PrerequisitesTo 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 (p. 4).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 (p. 8).

Be sure the AWS credentials map to an AWS Identity and Access Management (IAM) entity with access tothe AWS actions and resources described in this example.

This example assumes you have set the credentials in the AWS credentials profile file or in theAWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY environment variables on your local system.

Configure the SDKFor this example, add a require statement so that you can use the classes and methods provided by theAWS SDK for Ruby for Amazon S3. Then create an Aws::S3::Client object in the AWS Region where you

119

Page 126: AWS SDK for Ruby › sdk-for-ruby › latest › ...AWS SDK for Ruby to create Ruby applications that use AWS services. This guide contains the following sections: Getting Started

AWS SDK for Ruby Developer GuideUsing a Amazon S3 Bucket to Host a Website

want to create the bucket and the specified AWS profile. This code creates the Aws::S3::Client objectin the us-east-2 region.

An additional variable is also declared for the bucket used in this example. To help ensure thebucket name is unique across all AWS accounts, an additional require statement is added, and theSecureRandom module’s uuid method is called to generate a unique identifier. This identifier is insertedinto the name of the bucket to be created later in this example.

require 'aws-sdk-s3' # v2: require 'aws-sdk'

# Using Random UUIDs to Avoid Collisions when Testingrequire 'securerandom'bucket = "example-test-bucket-#{SecureRandom.uuid}"

# Setup

Create a BucketCall the create_bucket method, supplying the name of the bucket to create.

s3 = Aws::S3::Client.new(region: "us-west-2")

Get a Bucket Website’s ConfigurationCall the get_bucket_website method, supplying the name of the bucket. By default, a bucket is notconfigured as a website. To confirm this behavior, call the get_bucket_website method. This returnsan error, because there is no website configuration for the bucket.

# When Bucket Has No Website Configurationbegin s3.get_bucket_website(bucket: bucket)rescue Aws::S3::Errors::NoSuchWebsiteConfiguration puts "No bucket website configuration present."

Add an Object to a BucketCall the put_object method, supplying the name of the bucket and object, the object’s contents, and theobject’s access permissions set. This example adds two webpages to the bucket.

# Adding Simple Pages & Website Configurations3.put_object( bucket: bucket, key: "index.html", body: "Hello, Amazon S3!", acl: "public-read")s3.put_object( bucket: bucket, key: "error.html", body: "Page not found!", acl: "public-read"

Set a Bucket Website’s ConfigurationCall 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’sindex and error webpages.

120

Page 127: AWS SDK for Ruby › sdk-for-ruby › latest › ...AWS SDK for Ruby to create Ruby applications that use AWS services. This guide contains the following sections: Getting Started

AWS SDK for Ruby Developer GuideUsing a Amazon S3 Bucket to Host a Website

)s3.put_bucket_website( bucket: bucket, website_configuration: { index_document: { suffix: "index.html" }, error_document: { key: "error.html" } }

Access a Bucket Website’s DocumentsCall the Ruby Net::HTTP.get method, supplying the address to the document in the bucket website.

# Accessing as a Websiteindex_path = "http://#{bucket}.s3-website-us-west-2.amazonaws.com/"error_path = "http://#{bucket}.s3-website-us-west-2.amazonaws.com/nonexistent.html"

puts "Index Page Contents:\n#{Net::HTTP.get(URI(index_path))}\n\n"

Delete a Bucket WebsiteCall the delete_bucket_website method, supplying the name of the bucket.

# Removing Website Configuration

Delete a BucketCall the bucket method of an Aws::S3::Resource object, supplying the name of the bucket. This returns anAws::S3::Bucket object. Then call the Aws::S3::Bucket object’s delete method.

# Cleanupb = Aws::S3::Resource.new(region: "us-west-2").bucket(bucket)

Complete ExampleHere is the complete code for this example.

require 'aws-sdk-s3' # v2: require 'aws-sdk'

# Using Random UUIDs to Avoid Collisions when Testingrequire 'securerandom'bucket = "example-test-bucket-#{SecureRandom.uuid}"

# Setups3 = Aws::S3::Client.new(region: "us-west-2")s3.create_bucket(bucket: bucket)

# When Bucket Has No Website Configurationbegin s3.get_bucket_website(bucket: bucket)rescue Aws::S3::Errors::NoSuchWebsiteConfiguration puts "No bucket website configuration present."end

121

Page 128: AWS SDK for Ruby › sdk-for-ruby › latest › ...AWS SDK for Ruby to create Ruby applications that use AWS services. This guide contains the following sections: Getting Started

AWS SDK for Ruby Developer GuideAmazon SES Examples

# Adding Simple Pages & Website Configurations3.put_object( bucket: bucket, key: "index.html", body: "Hello, Amazon S3!", acl: "public-read")s3.put_object( bucket: bucket, key: "error.html", body: "Page not found!", acl: "public-read")s3.put_bucket_website( bucket: bucket, website_configuration: { index_document: { suffix: "index.html" }, error_document: { key: "error.html" } })

# Accessing as a Websiteindex_path = "http://#{bucket}.s3-website-us-west-2.amazonaws.com/"error_path = "http://#{bucket}.s3-website-us-west-2.amazonaws.com/nonexistent.html"

puts "Index Page Contents:\n#{Net::HTTP.get(URI(index_path))}\n\n"puts "Error Page Contents:\n#{Net::HTTP.get(URI(error_path))}\n\n"

# Removing Website Configurations3.delete_bucket_website(bucket: bucket)

# Cleanupb = Aws::S3::Resource.new(region: "us-west-2").bucket(bucket)

Amazon SES Examples Using the AWS SDK forRuby

Amazon Simple Email Service (Amazon SES) is an email platform that provides an easy, cost-effectiveway for you to send and receive email using your own email addresses and domains. You can use thefollowing examples to access Amazon SES using the AWS SDK for Ruby. For more information aboutAmazon SES, see the Amazon SES documentation.

Topics• Listing Valid Amazon SES Email Addresses (p. 122)• Verifying an Email Address in Amazon SES (p. 123)• Sending a Message to an Email Address in Amazon SES (p. 123)• Getting Amazon SES Statistics (p. 125)

Listing Valid Amazon SES Email AddressesThe following example demonstrates how to use the AWS SDK for Ruby to list the valid Amazon SESemail addresses.

122

Page 129: AWS SDK for Ruby › sdk-for-ruby › latest › ...AWS SDK for Ruby to create Ruby applications that use AWS services. This guide contains the following sections: Getting Started

AWS SDK for Ruby Developer GuideVerifying an Email Address in Amazon SES

require 'aws-sdk-ses' # v2: require 'aws-sdk'

# Create client in us-west-2 regionclient = Aws::SES::Client.new(region: 'us-west-2')

# Get up to 1000 identitiesids = client.list_identities({ identity_type: "EmailAddress"})

ids.identities.each do |email| attrs = client.get_identity_verification_attributes({ identities: [email] })

status = attrs.verification_attributes[email].verification_status

# Display email addresses that have been verified if status == "Success" puts email end

See the complete example on GitHub.

Verifying an Email Address in Amazon SESThe following example demonstrates how to use the AWS SDK for Ruby to verify an Amazon SES emailaddress.

require 'aws-sdk-ses' # v2: require 'aws-sdk'

# Replace [email protected] with a "To" address.recipient = "[email protected]"

# Create a new SES resource in the us-west-2 region.# Replace us-west-2 with the AWS Region you're using for Amazon SES.ses = Aws::SES::Client.new(region: 'us-west-2')

# Try to verify email address.begin ses.verify_email_identity({ email_address: recipient })

puts 'Email sent to ' + recipient

# If something goes wrong, display an error message.rescue Aws::SES::Errors::ServiceError => error puts "Email not sent. Error message: #{error}"end

See the complete example on GitHub.

Sending a Message to an Email Address in AmazonSESThe following example demonstrates how to use the AWS SDK for Ruby to send a message to an AmazonSES email address.

require 'aws-sdk-ses' # v2: require 'aws-sdk'

123

Page 130: AWS SDK for Ruby › sdk-for-ruby › latest › ...AWS SDK for Ruby to create Ruby applications that use AWS services. This guide contains the following sections: Getting Started

AWS SDK for Ruby Developer GuideSending a Message to an Email Address in Amazon SES

# Replace [email protected] with your "From" address.# This address must be verified with Amazon SES.sender = '[email protected]'

# Replace [email protected] with a "To" address. If your account# is still in the sandbox, this address must be verified.recipient = '[email protected]'

# Specify a configuration set. To use a configuration# set, uncomment the next line and line 74.# configsetname = "ConfigSet"

# The subject line for the email.subject = 'Amazon SES test (AWS SDK for Ruby)'

# The HTML body of the email.htmlbody = '<h1>Amazon SES test (AWS SDK for Ruby)</h1>'\ '<p>This email was sent with <a href="https://aws.amazon.com/ses/">'\ 'Amazon SES</a> using the <a href="https://aws.amazon.com/sdk-for-ruby/">'\ 'AWS SDK for Ruby</a>.'

# The email body for recipients with non-HTML email clients.textbody = 'This email was sent with Amazon SES using the AWS SDK for Ruby.'

# Specify the text encoding scheme.encoding = 'UTF-8'

# Create a new SES client in the us-west-2 region.# Replace us-west-2 with the AWS Region you're using for Amazon SES.ses = Aws::SES::Client.new(region: 'us-west-2')

# Try to send the email.begin # Provide the contents of the email. ses.send_email( destination: { to_addresses: [ recipient ] }, message: { body: { html: { charset: encoding, data: htmlbody }, text: { charset: encoding, data: textbody } }, subject: { charset: encoding, data: subject } }, source: sender, # Uncomment the following line to use a configuration set. # configuration_set_name: configsetname, )

puts 'Email sent to ' + recipient

124

Page 131: AWS SDK for Ruby › sdk-for-ruby › latest › ...AWS SDK for Ruby to create Ruby applications that use AWS services. This guide contains the following sections: Getting Started

AWS SDK for Ruby Developer GuideGetting Amazon SES Statistics

# If something goes wrong, display an error message.rescue Aws::SES::Errors::ServiceError => error puts "Email not sent. Error message: #{error}"end

See the complete example on GitHub.

Getting Amazon SES StatisticsThe following example demonstrates how to use the AWS SDK for Ruby to get statistics about AmazonSES. Use this information to avoid damaging your reputation when emails are bounced or rejected.

require 'aws-sdk-ses' # v2: require 'aws-sdk'

# Create a new SES resource in the us-west-2 region.# Replace us-west-2 with the AWS Region you're using for Amazon SES.ses = Aws::SES::Client.new(region: 'us-west-2')

begin # Get send statistics so we don't ruin our reputation resp = ses.get_send_statistics({})

dps = resp.send_data_points

puts "Got #{dps.count} data point(s):" puts

dps.each do |dp| puts "Timestamp: #{dp.timestamp}" #=> Time puts "Attempts: #{dp.delivery_attempts}" #=> Integer puts "Bounces: #{dp.bounces}" #=> Integer puts "Complaints: #{dp.complaints}" #=> Integer puts "Rejects: #{dp.rejects}" #-> Integer puts end

# If something goes wrong, display an error message.rescue Aws::SES::Errors::ServiceError => error puts "Error: #{error}"end

See the complete example on GitHub.

Amazon SNS Examples Using the AWS SDK forRuby

Amazon Simple Notification Service (Amazon SNS) is a web service that enables applications, endusers, and devices to instantly send and receive notifications from the cloud. You can use the followingexamples to access Amazon SNS using the AWS SDK for Ruby. For more information about Amazon SNS,see the Amazon SNS documentation.

Topics

• Getting Information about All Amazon SNS Topics (p. 126)

• Creating an Amazon SNS Topic (p. 126)

• Getting Information about All Subscriptions in an Amazon SNS Topic (p. 126)

125

Page 132: AWS SDK for Ruby › sdk-for-ruby › latest › ...AWS SDK for Ruby to create Ruby applications that use AWS services. This guide contains the following sections: Getting Started

AWS SDK for Ruby Developer GuideGetting Information about All Amazon SNS Topics

• Creating a Subscription in an Amazon SNS Topic (p. 126)

• Sending a Message to All Amazon SNS Topic Subscribers (p. 127)

• Enabling a Resource to Publish to an Amazon SNS Topic (p. 127)

Getting Information about All Amazon SNS TopicsThe following example lists the ARNs of your Amazon SNS topics in the us-west-2 region.

require 'aws-sdk-sns' # v2: require 'aws-sdk'

sns = Aws::SNS::Resource.new(region: 'us-west-2')

sns.topics.each do |topic| puts topic.arnend

Creating an Amazon SNS TopicThe following example creates the topic MyGroovyTopic in the us-west-2 region and displays theresulting topic ARN.

require 'aws-sdk-sns' # v2: 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 anAmazon SNS TopicThe following example lists the email addresses of the Amazon SNS subscriptions for the topic with theARN arn:aws:sns:us-west-2:123456789:MyGroovyTopic in the us-west-2 region.

require 'aws-sdk-sns' # v2: 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 an Amazon SNS TopicThe 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 [email protected] in the us-west-2 region, and displays the resulting ARN. Initially theARN value is pending confirmation. When the user confirms their email address, this value becomes atrue ARN.

126

Page 133: AWS SDK for Ruby › sdk-for-ruby › latest › ...AWS SDK for Ruby to create Ruby applications that use AWS services. This guide contains the following sections: Getting Started

AWS SDK for Ruby Developer GuideSending a Message to All Amazon SNS Topic Subscribers

require 'aws-sdk-sns' # v2: 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 Amazon SNS TopicSubscribersThe following example sends the message “Hello!” to all subscribers to the Amazon SNS topic with theARN arn:aws:sns:us-west-2:123456789:MyGroovyTopic.

require 'aws-sdk-sns' # v2: 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 an Amazon SNSTopicThe following example enables the resource with the ARN my-resource-arn to publish to the topicwith the ARN my-topic-arn in the us-west-2 region.

require 'aws-sdk-sns' # v2: require 'aws-sdk'

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 + '"} } }]}'

sns = Aws::SNS::Resource.new(region: 'us-west-2')

127

Page 134: AWS SDK for Ruby › sdk-for-ruby › latest › ...AWS SDK for Ruby to create Ruby applications that use AWS services. This guide contains the following sections: Getting Started

AWS SDK for Ruby Developer GuideAmazon SQS Examples

# Get topic by ARNtopic = sns.topic(my-topic-arn)

# Add policy to topictopic.set_attributes({ attribute_name: "Policy", attribute_value: policy})

Amazon SQS Examples Using the AWS SDK forRuby

Amazon Simple Queue Service (Amazon SQS) is a fully managed message queuing service that makes iteasy to decouple and scale microservices, distributed systems, and serverless applications. You can usethe following examples to access Amazon SQS using the AWS SDK for Ruby. For more information aboutAmazon SQS, see the Amazon SQS documentation.

Topics

• Getting Information about All Queues in Amazon SQS (p. 128)

• Creating a Queue in Amazon SQS (p. 129)

• Working with Queues in Amazon SQS (p. 129)

• Sending Messages in Amazon SQS (p. 130)

• Sending and Receiving Messages in Amazon SQS (p. 131)

• Receiving Messages in Amazon SQS (p. 132)

• Receiving Messages Using Long Polling in Amazon SQS (p. 133)

• Enabling Long Polling in Amazon SQS (p. 133)

• Receiving Messages Using the QueuePoller Class in Amazon SQS (p. 135)

• Redirecting Dead Letters in Amazon SQS (p. 136)

• Deleting a Queue in Amazon SQS (p. 136)

• Enabling a Resource to Publish to a Queue in Amazon SQS (p. 137)

• Working with a Dead Letter Queue in Amazon SQS (p. 137)

• Specifying the Message Visibility Timeout in Amazon SQS (p. 139)

Getting Information about All Queues in AmazonSQSThe following example lists the URLs, ARNs, messages available, and messages in flight of your AmazonSQS queues in the us-west-2 region.

require 'aws-sdk-sqs' # v2: 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

128

Page 135: AWS SDK for Ruby › sdk-for-ruby › latest › ...AWS SDK for Ruby to create Ruby applications that use AWS services. This guide contains the following sections: Getting Started

AWS SDK for Ruby Developer GuideCreating a Queue in Amazon SQS

# 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 putsend

Creating a Queue in Amazon SQSThe following example creates the Amazon SQS queue named MyGroovyQueue in the us-west-2region and displays its URL.

require 'aws-sdk-sqs' # v2: 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 SQSAmazon SQS provides highly scalable hosted queues for storing messages as they travel betweenapplications or microservices. To learn more about queues, see How Amazon SQS Queues Work.

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

1. Get a list of your queues by using Aws::SQS::Client#list_queues.

2. Create a queue by using Aws::SQS::Client#create_queue.

3. Get the queue’s URL by using Aws::SQS::Client#get_queue_url.

4. Delete the queue by using Aws::SQS::Client#delete_queue.

Prerequisites

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

• Installing the AWS SDK for Ruby (p. 4)

• Configuring the AWS SDK for Ruby (p. 8)

129

Page 136: AWS SDK for Ruby › sdk-for-ruby › latest › ...AWS SDK for Ruby to create Ruby applications that use AWS services. This guide contains the following sections: Getting Started

AWS SDK for Ruby Developer GuideSending Messages in Amazon SQS

Example

require 'aws-sdk-sqs' # v2: require 'aws-sdk'

sqs = Aws::SQS::Client.new(region: 'us-east-1')

# Get a list of your queues.sqs.list_queues.queue_urls.each do |queue_url| puts queue_urlend

# Create a queue.queue_name = "my-queue"

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 and try again." exit(false)end

# Get the queue's URL.queue_url = sqs.get_queue_url(queue_name: queue_name).queue_urlputs queue_url

# Delete the queue.sqs.delete_queue(queue_url: queue_url)

Sending Messages in Amazon SQSThe following example sends the message “Hello world” through the Amazon SQS queue with the URLURL in the us-west-2 region.

require 'aws-sdk-sqs' # v2: require 'aws-sdk'

sqs = Aws::SQS::Client.new(region: 'us-west-2')

sqs.send_message(queue_url: URL, message_body: 'Hello world')

The following example sends the messages “Hello world” and “How is the weather?” through theAmazon SQS queue with the URL URL in the us-west-2 region.

NoteIf your queue is a FIFO queue, you must include a message_group_id parameter in addition tothe id and message_body parameters.

require 'aws-sdk-sqs' # v2: require 'aws-sdk'

sqs = Aws::SQS::Client.new(region: 'us-west-2')

sqs.send_message_batch({ queue_url: URL,

130

Page 137: AWS SDK for Ruby › sdk-for-ruby › latest › ...AWS SDK for Ruby to create Ruby applications that use AWS services. This guide contains the following sections: Getting Started

AWS SDK for Ruby Developer GuideSending and Receiving Messages in Amazon SQS

entries: [ { id: 'msg1', message_body: 'Hello world' }, { id: 'msg2', message_body: 'How is the weather?' } ],})

Sending and Receiving Messages in Amazon SQSAfter you create a queue in Amazon SQS, you can send a message to it and then consume it. To learnmore, see Tutorial: Sending a Message to an Amazon SQS Queue and Tutorial: Receiving and Deleting aMessage from an Amazon SQS Queue.

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

1. Send a message to a queue by using Aws::SQS::Client#send_message.

NoteIf your queue is a FIFO queue, you must include a message_group_id parameter in addition tothe id and message_body parameters.

1. Receive the message in the queue by using Aws::SQS::Client#receive_message.

2. Display information about the message.

3. Delete the message from the queue by using Aws::SQS::Client#delete_message.

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

• Installing the AWS SDK for Ruby (p. 4)

• Configuring the AWS SDK for Ruby (p. 8)

You also need to create the queue my-queue, which you can do in the Amazon SQS console.

Example

require 'aws-sdk-sqs' # v2: require 'aws-sdk'

sqs = Aws::SQS::Client.new(region: 'us-east-1')

# Send a message to a queue.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,

131

Page 138: AWS SDK for Ruby › sdk-for-ruby › latest › ...AWS SDK for Ruby to create Ruby applications that use AWS services. This guide contains the following sections: Getting Started

AWS SDK for Ruby Developer GuideReceiving Messages in Amazon SQS

message_body: "Information about current NY Times fiction bestseller for week of 2016-12-11.", message_attributes: { "Title" => { string_value: "The Whistler", data_type: "String" }, "Author" => { string_value: "John Grisham", data_type: "String" }, "WeeksOn" => { string_value: "6", data_type: "Number" } } })rescue Aws::SQS::Errors::NonExistentQueue puts "A queue named '#{queue_name}' does not exist." exit(false)end

puts send_message_result.message_id

# Receive the message in the queue.receive_message_result = sqs.receive_message({ queue_url: queue_url, 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, receipt_handle: message.receipt_handle })end

Receiving Messages in Amazon SQSThe following example displays the body of up to 10 messages in the Amazon SQS queue with the URLURL in the us-west-2 region.

Notereceive_message does not guarantee to get all messages (see Properties of DistributedQueues), and by default does not delete the message.

require 'aws-sdk-sqs' # v2: 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|

132

Page 139: AWS SDK for Ruby › sdk-for-ruby › latest › ...AWS SDK for Ruby to create Ruby applications that use AWS services. This guide contains the following sections: Getting Started

AWS SDK for Ruby Developer GuideReceiving Messages Using Long Polling in Amazon SQS

puts m.bodyend

Receiving Messages Using Long Polling in AmazonSQSThe following example waits up to 10 seconds to display the bodies of up to 10 messages in the AmazonSQS queue with the URL URL in the us-west-2 region.

If you do not specify a wait time, the default value is 0 (Amazon SQS does not wait).

require 'aws-sdk-sqs' # v2: 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: 10)

resp.messages.each do |m| puts m.bodyend

Enabling Long Polling in Amazon SQSLong polling helps lower your cost of using Amazon SQS by reducing the number of empty responsesand eliminating false empty responses. For more information about long polling, see Amazon SQS LongPolling.

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

1. Create a queue and set it for long polling by using Aws::SQS::Client#create_queue.2. Set long polling for an existing queue by using Aws::SQS::Client#set_queue_attributes.3. Set long polling when receiving messages for a queue by using Aws::SQS::Client#receive_message.

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

• Installing the AWS SDK for Ruby (p. 4)• Configuring the AWS SDK for Ruby (p. 8)

You also need to create the queues existing-queue and receive-queue, which you can do in the AmazonSQS console.

Example

require 'aws-sdk-sqs' # v2: 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"

133

Page 140: AWS SDK for Ruby › sdk-for-ruby › latest › ...AWS SDK for Ruby to create Ruby applications that use AWS services. This guide contains the following sections: Getting Started

AWS SDK for Ruby Developer GuideEnabling Long Polling in Amazon SQS

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 exist."end

# Set long polling when receiving messages for a queue.

# 1. Using receive_message.begin receive_queue_name = "receive-queue" receive_queue_url = sqs.get_queue_url(queue_name: receive_queue_name).queue_url

puts "Begin receipt of any messages using receive_message..." receive_message_result = sqs.receive_message({ queue_url: receive_queue_url, attribute_names: ["All"], # Receive all available built-in message attributes. message_attribute_names: ["All"], # Receive any custom message attributes. max_number_of_messages: 10 # Receive up to 10 messages, if there are that many. })

puts "Received #{receive_message_result.messages.count} message(s)."rescue Aws::SQS::Errors::NonExistentQueue puts "Cannot receive messages using receive_message for a queue named '#{receive_queue_name}', as it does not exist."end

# 2. Using Aws::SQS::QueuePoller.begin puts "Begin receipt of any messages using Aws::SQS::QueuePoller..." puts "(Will keep polling until no more messages available for at least 60 seconds.)" poller = Aws::SQS::QueuePoller.new(receive_queue_url)

poller_stats = poller.poll({ 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:"

134

Page 141: AWS SDK for Ruby › sdk-for-ruby › latest › ...AWS SDK for Ruby to create Ruby applications that use AWS services. This guide contains the following sections: Getting Started

AWS SDK for Ruby Developer GuideReceiving Messages Using the

QueuePoller Class in Amazon SQS

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_queue_name}', as it does not exist."end

Receiving Messages Using the QueuePoller Class inAmazon SQSThe following example uses the QueuePoller utility class to display the body of all messages inthe Amazon SQS queue with the URL URL in the us-west-2 region, and deletes the message. Afterapproximately 15 seconds of inactivity, the script times out.

require 'aws-sdk-sqs' # v2: 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.bodyend

The following example loops through the Amazon SQS queue with the URL URL, and waits up toduration seconds.

You can get the correct URL by executing the Amazon SQS example in Getting Information about AllQueues in Amazon SQS (p. 128).

require 'aws-sdk-sqs' # v2: 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.bodyend

The following example loops through the Amazon SQS queue with the URL URL, and gives you up to thevisibility timeout seconds to process the message, represented by the method do_something.

require 'aws-sdk-sqs' # v2: require 'aws-sdk'

# Process the messagedef do_something(msg) puts msg.bodyend

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

poller = Aws::SQS::QueuePoller.new(URL)

poller.poll(visibility_timeout: timeout, idle_timeout: timeout + 1) do |msg|

135

Page 142: AWS SDK for Ruby › sdk-for-ruby › latest › ...AWS SDK for Ruby to create Ruby applications that use AWS services. This guide contains the following sections: Getting Started

AWS SDK for Ruby Developer GuideRedirecting Dead Letters in Amazon SQS

do_something(msg)end

The following example loops through the Amazon SQS queue with the URL URL, and changesthe visibility timeout seconds, for any message that needs additional processing by the methoddo_something2.

require 'aws-sdk-sqs' # v2: require 'aws-sdk'

# Process the messagedef do_something(_) trueend

# Do additional processingdef do_something2(msg) puts msg.bodyend

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

poller = Aws::SQS::QueuePoller.new(URL)

poller.poll(idle_timeout: timeout + 1) do |msg| if do_something(msg) # need more time for processing poller.change_message_visibility_timeout(msg, timeout)

do_something2(msg) endend

Redirecting Dead Letters in Amazon SQSThe following example redirects any dead letters from the queue with the URL URL to the queue with theARN ARN.

require 'aws-sdk-sqs' # v2: 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 SQSThe following example deletes the Amazon SQS queue with the URL URL in the us-west-2 region.

require 'aws-sdk-sqs' # v2: require 'aws-sdk'

sqs = Aws::SQS::Client.new(region: 'us-west-2')

sqs.delete_queue(queue_url: URL)

136

Page 143: AWS SDK for Ruby › sdk-for-ruby › latest › ...AWS SDK for Ruby to create Ruby applications that use AWS services. This guide contains the following sections: Getting Started

AWS SDK for Ruby Developer GuideEnabling a Resource to Publish to a Queue in Amazon SQS

Enabling a Resource to Publish to a Queue in AmazonSQSThe following example enables the resource with the ARN my-resource-arn to publish to the queuewith the ARN my-queue-arn and URL my-queue-url in the us-west-2 region.

require 'aws-sdk-sqs' # v2: 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 SQSAmazon 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 isolatethese messages in the dead letter queue to determine why their processing didn’t succeed. For moreinformation 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 usingAws::SQS::Client#set_queue_attributes.

3. Send a message to the existing queue by using Aws::SQS::Client#send_message.

4. Poll the queue by using Aws::SQS::QueuePoller.

5. Receive messages in the dead letter queue by using Aws::SQS::Client#receive_message.

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

137

Page 144: AWS SDK for Ruby › sdk-for-ruby › latest › ...AWS SDK for Ruby to create Ruby applications that use AWS services. This guide contains the following sections: Getting Started

AWS SDK for Ruby Developer GuideWorking with a Dead Letter Queue in Amazon SQS

• Installing the AWS SDK for Ruby (p. 4)

• Configuring the AWS SDK for Ruby (p. 8)

You also need to use the AWS Management Console to create the existing queue, my-queue.

NoteFor the sake of simplicity, this example code doesn’t demonstrateAws::SQS::Client#add_permission. In a real-world scenario, you should always restrict access toactions such as SendMessage, ReceiveMessage, DeleteMessage, and DeleteQueue. Not doing socould cause information disclosure, denial of service, or injection of messages into your queues.

Example

require 'aws-sdk-sqs' # v2: 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 dead letter queue. "deadLetterTargetArn" => dead_letter_queue_arn }.to_json

sqs.set_queue_attributes({ queue_url: queue_url, attributes: { "RedrivePolicy" => redrive_policy } })

rescue Aws::SQS::Errors::NonExistentQueue puts "A queue named '#{queue_name}' does not exist." exit(false)end

# Send a message to the queue.puts "Sending a message..."

138

Page 145: AWS SDK for Ruby › sdk-for-ruby › latest › ...AWS SDK for Ruby to create Ruby applications that use AWS services. This guide contains the following sections: Getting Started

AWS SDK for Ruby Developer GuideSpecifying the Message Visibility Timeout in Amazon SQS

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}" endend

# Check to see if Amazon SQS moved the message to the dead letter queue.receive_message_result = sqs.receive_message({ queue_url: dead_letter_queue_url, max_number_of_messages: 1})

if receive_message_result.messages.count > 0 puts "\n#{receive_message_result.messages[0].body}"else puts "\nNo messages received."end

Specifying the Message Visibility Timeout in AmazonSQSIn Amazon SQS, immediately after a message is received, it remains in the queue. To prevent otherconsumers from processing the message again, Amazon SQS sets a visibility timeout. This is a period oftime during which Amazon SQS prevents other consuming components from receiving and processingthe 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.

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

• Installing the AWS SDK for Ruby (p. 4)• Configuring the AWS SDK for Ruby (p. 8)

You also need to create the queue my-queue, which you can do in the Amazon SQS console.

139

Page 146: AWS SDK for Ruby › sdk-for-ruby › latest › ...AWS SDK for Ruby to create Ruby applications that use AWS services. This guide contains the following sections: Getting Started

AWS SDK for Ruby Developer GuideAmazon WorkDocs Examples

Example

require 'aws-sdk-sqs' # v2: 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_result_before.messages.count} message(s)."

receive_message_result_before.messages.each do |message| sqs.change_message_visibility({ queue_url: queue_url, receipt_handle: message.receipt_handle, visibility_timeout: 30 # This message will not be visible for 30 seconds after first receipt. }) end

# Try to retrieve the original messages after setting their visibility timeout. receive_message_result_after = sqs.receive_message({ queue_url: queue_url, max_number_of_messages: 10 })

puts "\nAfter attempting to change message visibility timeout: received #{receive_message_result_after.messages.count} message(s)."

rescue Aws::SQS::Errors::NonExistentQueue puts "Cannot receive messages for a queue named '#{receive_queue_name}', as it does not exist."end

Amazon WorkDocs ExamplesYou can use the following examples to access Amazon WorkDocs (Amazon WorkDocs) using the AWS SDKfor Ruby. For more information about Amazon WorkDocs, see the Amazon WorkDocs documentation.

You need your organization ID to use these examples. Get you organization ID from the AWS consoleusing the following steps:

• Select the AWS Directory Service• Select Directories

The organization ID is the Directory ID corresponding to your Amazon WorkDocs site.

Examples

Topics• Listing Users (p. 141)

140

Page 147: AWS SDK for Ruby › sdk-for-ruby › latest › ...AWS SDK for Ruby to create Ruby applications that use AWS services. This guide contains the following sections: Getting Started

AWS SDK for Ruby Developer GuideListing Users

• Listing User Docs (p. 141)

Listing UsersThe following example lists the names, email addresses, and root folders of all users in the organization.Choose Copy to save the code locally, or see the link to the complete example at the end of this topic.

Require the AWS SDK for Ruby module and create a Amazon WorkDocs client.

require 'aws-sdk-workdocs' # v2: require 'aws-sdk'

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

Call describe_users with your organization ID, and get all of the user names in ascending order.

# Set to the OrganizationId of your WorkDocs siteorgId = 'd-123456789c'

resp = client.describe_users({ organization_id: orgId, include: "ALL", # accepts ALL, ACTIVE_PENDING order: "ASCENDING", # accepts ASCENDING, DESCENDING sort: "USER_NAME", # accepts USER_NAME, FULL_NAME, STORAGE_LIMIT, USER_STATUS, STORAGE_USED})

Display the information about the users.

resp.users.each do |user| puts "First name: #{user.given_name}" puts "Last name: #{user.surname}" puts "Email: #{user.email_address}" puts "Root folder: #{user.root_folder_id}" putsend

See the complete example on GitHub.

Listing User DocsThe following example lists the documents for a user. Choose Copy to save the code locally, or see thelink to the complete example at the end of this topic.

Require the AWS SDK for Ruby module.

require 'aws-sdk-workdocs' # v2: require 'aws-sdk'

Create a helper method to get the root folder of a user.

def get_user_folder(client, orgId, user_email) root_folder = ''

resp = client.describe_users({ organization_id: orgId, })

141

Page 148: AWS SDK for Ruby › sdk-for-ruby › latest › ...AWS SDK for Ruby to create Ruby applications that use AWS services. This guide contains the following sections: Getting Started

AWS SDK for Ruby Developer GuideListing User Docs

# resp.users should have only one entry resp.users.each do |user| if user.email_address == user_email root_folder = user.root_folder_id end end

return root_folderend

Create a Amazon WorkDocs client.

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

Get the root folder for that user.

# Set to the email address of a useruser_email = 'someone@somewhere'

# Set to the OrganizationId of your WorkDocs site.orgId = 'd-123456789c'

user_folder = get_user_folder(client, orgId, user_email)

Call describe_folder_contents to get the contents of the folder in ascending order.

resp = client.describe_folder_contents({ folder_id: user_folder, # required sort: "NAME", # accepts DATE, NAME order: "ASCENDING", # accepts ASCENDING, DESCENDING})

Display the name, size (in bytes), last modified date, document ID and version ID for each document inthe user’s root folder.

resp.documents.each do |doc| md = doc.latest_version_metadata

puts "Name: #{md.name}" puts "Size (bytes): #{md.size}" puts "Last modified: #{doc.modified_timestamp}" puts "Doc ID: #{doc.id}" puts "Version ID: #{md.id}" putsend

See the complete example on GitHub.

142

Page 149: AWS SDK for Ruby › sdk-for-ruby › latest › ...AWS SDK for Ruby to create Ruby applications that use AWS services. This guide contains the following sections: Getting Started

AWS SDK for Ruby Developer GuideAmazon EC2 Tips and Tricks

AWS SDK for Ruby Tips and TricksThis section provides tips and tricks on using the AWS SDK for Ruby with AWS services.

Topics• Amazon EC2 Tips and Tricks (p. 143)

Amazon EC2 Tips and TricksThis section provides some tips to help you use the AWS SDK for Ruby with Amazon Elastic ComputeCloud (Amazon EC2) services. For more information about Amazon EC2, see the Amazon EC2 GettingStarted Guide.

Switching Elastic IPsThe following example associates the Elastic IP address with the instance represented by i-12345678.

ec2 = Aws::EC2::Client.new

resp = ec2.allocate_addressec2.associate_address(instance_id:"i-12345678", allocation_id: resp.allocation_id)

143

Page 150: AWS SDK for Ruby › sdk-for-ruby › latest › ...AWS SDK for Ruby to create Ruby applications that use AWS services. This guide contains the following sections: Getting Started

AWS SDK for Ruby Developer GuideData Protection

Security for this AWS Product orService

Cloud security at Amazon Web Services (AWS) is the highest priority. As an AWS customer, you benefitfrom a data center and network architecture that is built to meet the requirements of the mostsecurity-sensitive organizations. Security is a shared responsibility between AWS and you. The SharedResponsibility Model describes this as Security of the Cloud and Security in the Cloud.

Security of the Cloud– AWS is responsible for protecting the infrastructure that runs all of the servicesoffered in the AWS Cloud and providing you with services that you can use securely. Our securityresponsibility is the highest priority at AWS, and the effectiveness of our security is regularly tested andverified by third-party auditors as part of the AWS Compliance Programs.

Security in the Cloud– Your responsibility is determined by the AWS service you are using, and otherfactors including the sensitivity of your data, your organization’s requirements, and applicable laws andregulations.

Topics• Data Protection in this AWS Product or Service (p. 144)• Identity and Access Management for this AWS Product or Service (p. 145)• Compliance Validation for this AWS Product or Service (p. 145)• Resilience for this AWS Product or Service (p. 146)• Infrastructure Security for this AWS Product or Service (p. 146)• Using TLS 1.2 in this AWS Product or Service (p. 146)

Data Protection in this AWS Product or ServiceThis AWS product or service conforms to the shared responsibility model, which includes regulationsand guidelines for data protection. Amazon Web Services (AWS) is responsible for protecting theglobal infrastructure that runs all the AWS services. AWS maintains control over data hosted on thisinfrastructure, including the security configuration controls for handling customer content and personaldata. AWS customers and APN partners, acting either as data controllers or data processors, areresponsible for any personal data that they put in the AWS Cloud.

For data protection purposes, we recommend that you protect AWS account credentials and set upindividual user accounts with AWS Identity and Access Management (IAM), so that each user is given onlythe permissions necessary to fulfill their job duties. We also recommend that you secure your data in thefollowing ways:

• Use multi-factor authentication (MFA) with each account.• Use SSL/TLS to communicate with AWS resources.• Set up API and user activity logging with AWS CloudTrail.• Use AWS encryption solutions, along with all default security controls within AWS services.• Use advanced managed security services such as Amazon Macie, which assists in discovering and

securing personal data that is stored in Amazon S3.

We strongly recommend that you never put sensitive identifying information, such as your customers’account numbers, into free-form fields such as a Name field. This includes when you work with this

144

Page 151: AWS SDK for Ruby › sdk-for-ruby › latest › ...AWS SDK for Ruby to create Ruby applications that use AWS services. This guide contains the following sections: Getting Started

AWS SDK for Ruby Developer GuideIdentity and Access Management

AWS product or service or other AWS services using the console, API, AWS CLI, or AWS SDKs. Any datathat you enter into this AWS product or service or other services might get picked up for inclusion indiagnostic logs. When you provide a URL to an external server, don’t include credentials information inthe URL to validate your request to that server.

For more information about data protection, see the AWS Shared Responsibility Model and GDPR blogpost on the AWS Security Blog.

Identity and Access Management for this AWSProduct or Service

AWS Identity and Access Management (IAM) is an Amazon Web Services (AWS) service that helpsan administrator securely control access to AWS resources. IAM administrators control who can beauthenticated (signed in) and authorized (have permissions) to use resources AWS services. IAM is an AWSservice that you can use with no additional charge.

To use this AWS product or service to access AWS, you need an AWS account and AWS credentials. Toincrease the security of your AWS account, we recommend that you use an IAM user to provide accesscredentials instead of using your AWS account credentials.

For details about working with IAM, see IAM.

For an overview of IAM users and why they are important for the security of your account, see AWSSecurity Credentials in the Amazon Web Services General Reference.

This AWS product or service follows the shared responsibility model through the specific Amazon WebServices (AWS) services it supports. For AWS service security information, see the AWS service securitydocumentation page and AWS services that are in scope of AWS compliance efforts by complianceprogram.

Compliance Validation for this AWS Product orService

This AWS product or service follows the shared responsibility model through the specific Amazon WebServices (AWS) services it supports. For AWS service security information, see the AWS service securitydocumentation page and AWS services that are in scope of AWS compliance efforts by complianceprogram.

The security and compliance of Amazon Web Services (AWS) services is assessed by third-party auditorsas part of multiple AWS compliance programs. These include SOC, PCI, FedRAMP, HIPAA, and others.AWS provides a frequently updated list of AWS services in scope of specific compliance programs at AWSServices in Scope by Compliance Program.

Third-party audit reports are available for you to download using AWS Artifact. For more information,see Downloading Reports in AWS Artifact.

For more information about AWS compliance programs, see AWS Compliance Programs.

Your compliance responsibility when using this AWS product or service to access an AWS service isdetermined by the sensitivity of your data, your organization’s compliance objectives, and applicablelaws and regulations. If your use of an AWS service is subject to compliance with standards such asHIPAA, PCI, or FedRAMP, AWS provides resources to help:

145

Page 152: AWS SDK for Ruby › sdk-for-ruby › latest › ...AWS SDK for Ruby to create Ruby applications that use AWS services. This guide contains the following sections: Getting Started

AWS SDK for Ruby Developer GuideResilience

• Security and Compliance Quick Start Guides– Deployment guides that discuss architecturalconsiderations and provide steps for deploying security-focused and compliance-focused baselineenvironments on AWS.

• Architecting for HIPAA Security and Compliance Whitepaper– A whitepaper that describes howcompanies can use AWS to create HIPAA-compliant applications.

• AWS Compliance Resources– A collection of workbooks and guides that might apply to your industryand location.

• AWS Config– A service that assesses how well your resource configurations comply with internalpractices, industry guidelines, and regulations.

• AWS Security Hub– A comprehensive view of your security state within AWS that helps you check yourcompliance with security industry standards and best practices.

Resilience for this AWS Product or ServiceThe Amazon Web Services (AWS) global infrastructure is built around AWS Regions and AvailabilityZones.

AWS Regions provide multiple physically separated and isolated Availability Zones, which are connectedwith low-latency, high-throughput, and highly redundant networking.

With Availability Zones, you can design and operate applications and databases that automatically failover between Availability Zones without interruption. Availability Zones are more highly available, faulttolerant, and scalable than traditional single or multiple data center infrastructures.

For more information about AWS Regions and Availability Zones, see AWS Global Infrastructure.

This AWS product or service follows the shared responsibility model through the specific Amazon WebServices (AWS) services it supports. For AWS service security information, see the AWS service securitydocumentation page and AWS services that are in scope of AWS compliance efforts by complianceprogram.

Infrastructure Security for this AWS Product orService

This AWS product or service follows the shared responsibility model through the specific Amazon WebServices (AWS) services it supports. For AWS service security information, see the AWS service securitydocumentation page and AWS services that are in scope of AWS compliance efforts by complianceprogram.

For information about AWS security processes, see the AWS: Overview of Security Processes whitepaper.

Using TLS 1.2 in this AWS Product or ServiceCommunication between AWS SDK for Ruby and AWS is secured using Secure Sockets Layer (SSL) orTransport Layer Security (TLS). All versions of SSL, and versions of TLS prior to 1.2, have vulnerabilitiesthat can compromise the security of your communication with AWS. For this reason, you should makesure that you are using the AWS SDK for Ruby with a version of Ruby that supports TLS v1.2 or later.

Ruby uses the OpenSSL library to secure HTTP connections. Supported versions of Ruby (1.9.3 and later)installed through system package managers (yum, apt, etc.), an official installer, or Ruby managers(rbenv, RVM, etc.) typically incorporate OpenSSL 1.0.1 or later, which supports TLS 1.2.

146

Page 153: AWS SDK for Ruby › sdk-for-ruby › latest › ...AWS SDK for Ruby to create Ruby applications that use AWS services. This guide contains the following sections: Getting Started

AWS SDK for Ruby Developer GuideChecking OpenSSL version

When used with a supported version of Ruby with OpenSSL 1.0.1 or later, AWS SDK for Ruby prefers TLS1.2, and uses the highest version of SSL or TLS supported by both the client and server, which is alwaysat least TLS 1.2 for AWS services. (The SDK uses the Ruby Net::HTTP class with use_ssl=true.)

Checking OpenSSL versionTo make sure your installation of Ruby is using OpenSSL 1.0.1 or later, enter this command:

ruby -r openssl -e 'puts OpenSSL::OPENSSL_VERSION'

An alternative way to get the OpenSSL version is to query the openssl executable directly. First, locatethe appropriate executable using the following command.

ruby -r rbconfig -e 'puts RbConfig::CONFIG["configure_args"]'

The output should have --with-openssl-dir=/path/to/openssl indicating the location of theOpenSSL installation. Make a note of this path. To check the version of OpenSSL, enter the followingcommands.

cd /path/to/opensslbin/openssl version

This latter method may not work with all installations of Ruby.

Upgrading TLS SupportIf the version of OpenSSL used by your Ruby is less than 1.0.1, upgrade your Ruby or OpenSSLinstallation using your system package manager, Ruby installer, or Ruby manager as described in Ruby’sinstallation guide. If you are installing Ruby from source, install the latest OpenSSL first, and pass --with-openssl-dir=/path/to/upgraded/openssl when running ./configure.

147

Page 154: AWS SDK for Ruby › sdk-for-ruby › latest › ...AWS SDK for Ruby to create Ruby applications that use AWS services. This guide contains the following sections: Getting Started

AWS SDK for Ruby Developer Guide

Document HistoryTo view the list of changes to the AWS SDK for Ruby and its documentation, see the Change logs undereach gem in the aws/aws-sdk-ruby repository in GitHub.

148