• 沒有找到結果。

AWS SDK for Ruby

N/A
N/A
Protected

Academic year: 2022

Share "AWS SDK for Ruby"

Copied!
225
0
0

加載中.... (立即查看全文)

全文

(1)

AWS SDK for Ruby

Developer Guide

AWS SDK for Ruby: Developer Guide

Copyright © Amazon Web Services, Inc. and/or its affiliates. All rights reserved.

(2)

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

(3)

Table of Contents

AWS SDK for Ruby Developer Guide ... 1

Using the AWS SDK for Ruby with AWS Cloud9 ... 1

About This Guide ... 1

Additional Documentation and Resources ... 1

Deploying to the AWS Cloud ... 2

Maintenance and support for SDK major versions ... 2

Getting Started ... 3

Quick Start Guide ... 3

Write the Code ... 3

Run the Code ... 3

Note for Windows Users ... 3

Installing the SDK ... 4

Prerequisites ... 4

Installing the SDK ... 4

Hello World Tutorial ... 4

Using the AWS SDK for Ruby in Your Program ... 5

Creating an Amazon S3 Resource ... 5

Creating a Bucket ... 5

Adding a File to the Bucket ... 5

Listing the Contents of a Bucket ... 5

Complete Program ... 5

Running the Program ... 7

Next Steps ... 7

Configuring the SDK ... 8

Get your AWS access keys ... 8

To get your access key ID and secret access key ... 8

Setting AWS Credentials ... 8

Setting Shared Credentials ... 9

Setting Credentials Using Environment Variables ... 9

Setting Credentials Using Aws.config ... 9

Changing your Credentials Location ... 10

Setting Credentials in a Client Object ... 10

Setting Credentials Using IAM ... 10

Creating an AWS STS Access Token ... 10

Setting a Region ... 11

Setting the Region Using Environment Variables ... 11

Setting the Region Using Aws.config ... 11

Setting the Region in a Client or Resource Object ... 11

Setting a Nonstandard Endpoint ... 11

Using AWS Cloud9 with the SDK ... 12

Step 1: Set up Your AWS Account to Use AWS Cloud9 ... 12

Step 2: Set up Your AWS Cloud9 Development Environment ... 12

Step 3: Set up the AWS SDK for Ruby ... 12

Step 4: Download Example Code ... 13

Step 5: Run Example Code ... 13

Using the SDK ... 14

Using the AWS SDK for Ruby REPL Tool ... 14

Using the SDK with Ruby on Rails ... 14

Migrating from Version 1 or 2 to Version 3 of the AWS SDK for Ruby ... 15

Side-by-Side Usage ... 15

General Differences ... 15

Client Differences ... 15

Resource Differences ... 16

Debugging Tip: Getting Wire Trace Information from a Client ... 17

(4)

Stubbing Client Responses and Errors ... 18

Stubbing Client Responses ... 18

Stubbing Client Errors ... 19

Paging Response Data ... 19

Paged Responses Are Enumerable ... 19

Handling Paged Responses Manually ... 19

Paged Data Classes ... 20

Using Waiters ... 20

Invoking a Waiter ... 20

Wait Failures ... 20

Configuring a Waiter ... 21

Extending a Waiter ... 21

Specifying a Client Timeout Duration ... 22

Code Examples ... 23

AWS CloudTrail Examples ... 23

Listing the CloudTrail Trails ... 23

Creating a CloudTrail Trail ... 24

Listing CloudTrail Trail Events ... 26

Deleting a CloudTrail Trail ... 27

Amazon CloudWatch Examples ... 28

Getting Information about Amazon CloudWatch Alarms ... 28

Creating an Amazon CloudWatch Alarm ... 29

Enabling and Disabling Amazon CloudWatch Alarm Actions ... 32

Getting Information about Custom Metrics for Amazon CloudWatch ... 34

Sending Events to Amazon CloudWatch Events ... 37

AWS CodeBuild Examples ... 50

Getting Information about All AWS CodeBuild Projects ... 50

Building an AWS CodeBuild Project ... 51

Listing AWS CodeBuild Project Builds ... 51

Amazon DynamoDB Examples ... 52

Getting Information about All Amazon DynamoDB Tables ... 52

Creating an Amazon DynamoDB Table ... 54

Adding an Item to an Amazon DynamoDB Table ... 55

Loading Items from a JSON File into an Amazon DynamoDB Table ... 57

Reading an Item in an Amazon DynamoDB Table ... 59

Updating an Amazon DynamoDB Table Item ... 60

Deleting an Amazon DynamoDB Table Item ... 61

Deleting an Amazon DynamoDB Table ... 62

Amazon EC2 Examples ... 63

Creating an Amazon EC2 VPC ... 63

Creating an Internet Gateway and Attaching It to a VPC in Amazon EC2 ... 65

Creating a Public Subnet for Amazon EC2 ... 66

Creating an Amazon EC2 Route Table and Associating It with a Subnet ... 68

Using Elastic IP Addresses in Amazon EC2 ... 70

Creating an Amazon EC2 Security Group ... 74

Working with Amazon EC2 Security Groups ... 76

Working with Key Pairs in Amazon EC2 ... 81

Getting Information about All Amazon EC2 Instances ... 84

Getting Information about All Amazon EC2 Instances with a Specific Tag Value ... 85

Getting Information about a Specific Amazon EC2 Instance ... 86

Creating an Amazon EC2 Instance ... 87

Stopping an Amazon EC2 Instance ... 89

Starting an Amazon EC2 Instance ... 91

Rebooting an Amazon EC2 Instance ... 92

Managing Amazon EC2 Instances ... 93

Terminating an Amazon EC2 Instance ... 96

Getting Information about Regions and Availability Zones for Amazon EC2 ... 98

(5)

AWS Elastic Beanstalk Examples ... 100

Getting Information about All Applications in AWS Elastic Beanstalk ... 100

Getting Information about a Specific Application in AWS Elastic Beanstalk ... 100

Updating a Ruby on Rails Application for AWS Elastic Beanstalk ... 101

AWS Identity and Access Management (IAM) Examples ... 102

Getting Information about IAM Users ... 103

Listing IAM Users who are Administrators ... 104

Adding a New IAM User ... 107

Create User Access Keys for an IAM User ... 108

Adding a Managed Policy to an IAM User ... 109

Creating an IAM Role ... 110

Managing IAM Users ... 111

Working with IAM Policies ... 114

Managing IAM Access Keys ... 117

Working with IAM Server Certificates ... 121

Managing IAM Account Aliases ... 124

AWS KMS Examples ... 126

Creating a CMK in AWS KMS ... 126

Encrypting Data in AWS KMS ... 127

Decrypting a Data Blob in AWS KMS ... 128

Re-encrypting a Data Blob in AWS KMS ... 128

AWS Lambda Examples ... 129

Displaying Information about All Lambda Functions ... 129

Creating a Lambda Function ... 130

Running a Lambda Function ... 131

Configuring a Lambda Function to Receive Notifications ... 132

Amazon Polly Examples ... 133

Getting a List of Voices ... 133

Getting a List of Lexicons ... 134

Synthesizing Speech ... 135

Amazon RDS Examples ... 136

Getting Information about All Amazon RDS Instances ... 136

Getting Information about All Amazon RDS Snapshots ... 137

Getting Information about All Amazon RDS Clusters and Their Snapshots ... 137

Getting Information about All Amazon RDS Security Groups ... 138

Getting Information about All Amazon RDS Subnet Groups ... 139

Getting Information about All Amazon RDS Parameter Groups ... 139

Creating a Snapshot of an Amazon RDS Instance ... 140

Creating a Snapshot of an Amazon RDS Cluster ... 140

Amazon S3 Examples ... 141

Getting Information about All Amazon S3 Buckets ... 141

Getting Information about All Amazon S3 Buckets in a Region ... 142

Creating and Using an Amazon S3 Bucket ... 143

Determining Whether an Amazon S3 Bucket Exists ... 147

Getting Information about Amazon S3 Bucket Objects ... 149

Uploading an Object to an Amazon S3 Bucket ... 150

Uploading an Object with Metadata to an Amazon S3 Bucket ... 151

Downloading an Object from an Amazon S3 Bucket into a File ... 152

Changing the Properties for an Amazon S3 Bucket Object ... 153

Encrypting Amazon S3 Bucket Items ... 154

Triggering a Notification When an Item is Added to an Amazon S3 Bucket ... 167

Creating a LifeCycle Rule Configuration Template for an Amazon S3 Bucket ... 169

Creating an Amazon S3 Bucket Policy with Ruby ... 171

Configuring an Amazon S3 Bucket for CORS ... 175

Managing Amazon S3 Bucket and Object Access Permissions ... 177

Using a Amazon S3 Bucket to Host a Website ... 180

Amazon SES Examples ... 182

(6)

Listing Valid Amazon SES Email Addresses ... 182

Verifying an Email Address in Amazon SES ... 183

Sending a Message to an Email Address in Amazon SES ... 183

Getting Amazon SES Statistics ... 185

Amazon SNS Examples ... 186

Getting Information about All Amazon SNS Topics ... 186

Creating an Amazon SNS Topic ... 186

Getting Information about All Subscriptions in an Amazon SNS Topic ... 187

Creating a Subscription in an Amazon SNS Topic ... 187

Sending a Message to All Amazon SNS Topic Subscribers ... 188

Enabling a Resource to Publish to an Amazon SNS Topic ... 188

Amazon SQS Examples ... 189

Getting Information about All Queues in Amazon SQS ... 190

Creating a Queue in Amazon SQS ... 191

Working with Queues in Amazon SQS ... 191

Sending Messages in Amazon SQS ... 193

Sending and Receiving Messages in Amazon SQS ... 195

Receiving Messages in Amazon SQS ... 197

Receiving Messages Using Long Polling in Amazon SQS ... 198

Enabling Long Polling in Amazon SQS ... 198

Receiving Messages Using the QueuePoller Class in Amazon SQS ... 200

Redirecting Dead Letters in Amazon SQS ... 202

Deleting a Queue in Amazon SQS ... 203

Enabling a Resource to Publish to a Queue in Amazon SQS ... 203

Working with a Dead Letter Queue in Amazon SQS ... 204

Specifying the Message Visibility Timeout in Amazon SQS ... 206

Amazon WorkDocs Examples ... 208

Listing Users ... 208

Listing User Docs ... 209

Tips and Tricks ... 211

Amazon EC2 Tips and Tricks ... 211

Switching Elastic IPs ... 211

Security ... 212

Data Protection ... 212

Identity and Access Management ... 213

Compliance Validation ... 213

Resilience ... 214

Infrastructure Security ... 214

Using TLS 1.2 ... 214

Checking the OpenSSL version ... 215

Upgrading TLS support ... 215

S3 Encryption Client Migration ... 215

Migration Overview ... 215

Update Existing Clients to Read New Formats ... 215

Migrate Encryption and Decryption Clients to V2 ... 216

Document History ... 219

(7)

AWS SDK for Ruby Developer Guide

Welcome to the AWS SDK for Ruby.

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

Using the AWS SDK for Ruby with AWS Cloud9

AWS Cloud9 is a web-based integrated development environment (IDE) that contains a collection of tools 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. 12) for information on using AWS Cloud9 with the AWS SDK for Ruby.

About This Guide

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

This guide contains the following sections:

Getting Started with the AWS SDK for Ruby (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. 14)

Provides general information about developing applications with the AWS SDK for Ruby.

AWS SDK for Ruby Code Examples (p. 23)

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

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

Provides helpful information for using the AWS SDK for Ruby with AWS services.

Document History (p. 219)

Describes the history of this document.

Additional Documentation and Resources

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

(8)

• 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 Cloud

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

Maintenance and support for SDK major versions

For information about maintenance and support for SDK major versions and their underlying dependencies, see the following in the AWS SDKs and Tools Shared Configuration and Credentials Reference Guide:

• AWS SDKs and Tools Maintenance Policy

• AWS SDKs and Tools Version Support Matrix

(9)

Getting Started with the AWS SDK for Ruby

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

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 Ruby

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

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

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

Write the Code

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

require 'aws-sdk-s3' # 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 Code

Enter the following command to execute buckets.rb.

ruby buckets.rb

Note for Windows Users

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

C:\Ruby>ruby buckets.rb

C:/Ruby200-x64/lib/ruby/2.0.0/net/http.rb:921:in `connect': SSL_connect returned=1 errno=0 state=SSLv3 read server certificate B: certificate verify failed

(Seahorse::Client::NetworkingError)

(10)

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 the aws-sdk-core gem to use the bundled certificate.

Installing the AWS SDK for Ruby

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

Prerequisites

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

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

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

2. Follow the online instructions.

Installing the SDK

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

gem 'aws-sdk'

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

gem install aws-sdk

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

sudo gem install aws-sdk

Hello World Tutorial for the AWS SDK for Ruby

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

(11)

Using the AWS SDK for Ruby in Your Program

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

require 'aws-sdk'

Creating an Amazon S3 Resource

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

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

Creating a Bucket

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

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

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

Adding a File to the Bucket

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

name = File.basename 'my_file'

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

Listing the Contents of a Bucket

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

my_bucket.objects.limit(50).each do |obj|

puts " #{obj.key} => #{obj.etag}"

end

Complete Program

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

require 'aws-sdk'

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

(12)

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 required bucket_name = nil

if ARGV.length > 0 bucket_name = ARGV[0]

else

puts USAGE exit 1 end

# The operation to perform on the bucket operation = 'list' # default

operation = ARGV[1] if (ARGV.length > 1)

# The file name to use with 'upload' file = nil

file = ARGV[2] if (ARGV.length > 2)

# Get an Amazon S3 resource

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

# Get the bucket by name bucket = s3.bucket(bucket_name) case operation

when 'create'

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

puts "The bucket '%s' already exists!" % bucket_name else

bucket.create

puts "Created new S3 bucket: %s" % bucket_name end

when 'upload' if file == nil

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

exit end

if bucket.exists?

name = File.basename file

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

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

else

obj = s3.bucket(bucket_name).object(name)

(13)

obj.upload_file(file)

puts "Uploaded '%s' to S3!" % name end

else

NO_SUCH_BUCKET % bucket_name end

when 'list'

if bucket.exists?

# Enumerate the bucket contents and object etags puts "Contents of '%s':" % bucket_name

puts ' Name => GUID'

bucket.objects.limit(50).each do |obj|

puts " #{obj.key} => #{obj.etag}"

end else

NO_SUCH_BUCKET % bucket_name end

else

puts "Unknown operation: '%s'!" % operation puts USAGE

end

Running the Program

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

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

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

ruby hello-s3.rb bucket-name create

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

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

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

Next Steps

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

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

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

• Use the code in Adding a File to the Bucket (p. 5) to confirm the item exists in the bucket, and then update that bucket item.

(14)

Configuring the AWS SDK for Ruby

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

Get your AWS access keys

Access keys consist of an access key ID and secret access key, which are used to sign programmatic requests that you make to AWS. If you don’t have access keys, you can create them by using the

Management Console. We recommend that you use IAM access keys instead of AWS root account access keys. IAM lets you securely control access to AWS services and resources in your AWS account.

Note

To create access keys, you must have permissions to perform the required IAM actions. For more information, see Granting IAM User Permission to Manage Password Policy and Credentials in the IAM User Guide.

To get your access key ID and secret access key

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

Important

Keep the keys confidential to protect your AWS account, and never email them. Do not share them 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 the IAM User Guide.

• AWS Security Credentials in the AWS General Reference.

Setting AWS Credentials

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

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

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

(15)

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. 9)

The following sections describe the various ways you can set credentials, starting with the most flexible approach. For more information about AWS credentials and recommended approaches for credential management, see AWS Security Credentials in the AWS General Reference.

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

Setting Shared Credentials

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

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

~/.aws/credentials

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

%HOMEPATH%\.aws\credentials

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

[default]

aws_access_key_id = your_access_key_id

aws_secret_access_key = your_secret_access_key

Setting Credentials Using Environment Variables

Set the AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY environment variables.

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

export AWS_ACCESS_KEY_ID=your_access_key_id

export AWS_SECRET_ACCESS_KEY=your_secret_access_key

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

set AWS_ACCESS_KEY_ID=your_access_key_id

set AWS_SECRET_ACCESS_KEY=your_secret_access_key

Setting Credentials Using Aws.config

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

(16)

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

Aws.config.update({

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

Changing your Credentials Location

You 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 Object

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

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

s3 = Aws::S3::Client.new(

access_key_id: 'your_access_key_id', secret_access_key: 'your_secret_access_key' )

Setting Credentials Using IAM

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

Creating an AWS STS Access Token

Use the Aws::AssumeRoleCredentials method to create an AWS Security Token Service (AWS STS) access token.

The following example uses an access token to create an Amazon S3 client object, where

linked::account::arn is the Amazon Resource Name (ARN) of the role to assume and session- name is an identifier for the assumed role session.

role_credentials = Aws::AssumeRoleCredentials.new(

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

)

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

(17)

Setting a Region

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

• Setting the Region in a Client or Resource Object (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 Variables

Set the region by setting the AWS_REGION environment variable.

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

export AWS_REGION=us-west-2

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

set AWS_REGION=us-west-2

Setting the Region Using Aws.config

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

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

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

Setting the Region in a Client or Resource Object

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

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

Setting a Nonstandard Endpoint

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

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

(18)

Using AWS Cloud9 with the AWS SDK for Ruby

You can use AWS Cloud9 with the AWS SDK for Ruby to write and run your Ruby code using just a browser. AWS Cloud9 includes tools such as a code editor and terminal. Because the AWS Cloud9 IDE is 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. 12)

• Step 2: Set up Your AWS Cloud9 Development Environment (p. 12)

• Step 3: Set up the AWS SDK for Ruby (p. 12)

• Step 4: Download Example Code (p. 13)

• Step 5: Run Example Code (p. 13)

Step 1: Set up Your AWS Account to Use AWS Cloud9

Start to use AWS Cloud9 by signing in to the AWS Cloud9 console as an AWS Identity and Access

Management (IAM) entity (for example, an IAM user) in your AWS account who has access permissions for AWS Cloud9.

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

Step 2: Set up Your AWS Cloud9 Development Environment

After you sign in to the AWS Cloud9 console, use the console to create an AWS Cloud9 development environment. 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.

Note

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

Step 3: Set up the AWS SDK for Ruby

After AWS Cloud9 opens the IDE for your development environment, use the IDE to set up the AWS SDK for Ruby in your environment, as follows.

(19)

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 you chose 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 the option to Create a new instance for environment (EC2), earlier in this topic.)

sudo yum -y install ruby

Step 4: Download Example Code

Use the terminal you opened in the previous step to download example code for the AWS SDK for Ruby into the AWS Cloud9 development environment.

To do this, run the following command. This command downloads a copy of all of the code examples used 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 the

ENVIRONMENT_NAME/aws-doc-sdk-examples/ruby directory, where ENVIRONMENT_NAME is the name of your development environment.

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

Step 5: Run Example Code

To run code in your AWS Cloud9 development environment, see Run Your Code in the AWS Cloud9 User Guide.

(20)

Using the AWS SDK for Ruby

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

Topics

• Using the AWS SDK for Ruby REPL Tool (p. 14)

• Using the SDK with Ruby on Rails (p. 14)

• Migrating from Version 1 or 2 to Version 3 of the AWS SDK for Ruby (p. 15)

• Debugging Tip: Getting Wire Trace Information from a Client (p. 17)

• Stubbing Client Responses and Errors (p. 18)

• Paging Response Data (p. 19)

• Using Waiters (p. 20)

• Specifying a Client Timeout Duration (p. 22)

Using the AWS SDK for Ruby REPL Tool

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

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

Use the following command to install pry.

gem install pry

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

aws-v3.rb aws-v3.rb -v

The second command line invokes the REPL with extensive HTTP wire logging, which provides

information about the communication between the AWS SDK for Ruby and AWS. Use this command line with caution, however, because it also adds overhead that can make your code run slower.

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

Using the SDK with Ruby on Rails

Ruby on Rails provides a web development framework 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 Elastic Beanstalk, AWS OpsWorks, AWS CodeDeploy, or the AWS Rails Provisioner to deploy and run your Rails applications 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.

(21)

Migrating from Version 1 or 2 to Version 3 of the AWS 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 version 3.

Side-by-Side Usage

It isn’t necessary to replace the version 1 or 2 of the AWS SDK for Ruby with version 3. You can use them together in the same application. See this blog post for more information.

A quick example follows.

require 'aws-sdk-v1' # version 1 require 'aws-sdk' # version 2 require 'aws-sdk-s3' # version 3 s3 = AWS::S3::Client.new # version 1 s3 = 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 valid migration strategy is to only write new code against the version 3 SDK.

General Differences

Version 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 an ArgumentError. For example:

# version 1

AWS::S3::Client.new(http_reed_timeout: 10)

# oops, typo'd option is ignored

# version 2

Aws::S3::Client.new(http_reed_timeout: 10)

# => raises ArgumentError

Client Differences

There 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 service clients will have compatible interfaces after client construction. Some important differences:

(22)

• Aws::S3::Client - The version 1 Amazon S3 client class was hand-coded. Version 2 is generated from 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. For example:

# version 1

resp = AWS::EC2::Client.new.describe_security_groups resp.security_group_set

#=> [...]

# version 2

resp = Aws::EC2::Client.new.describe_security_groups resp.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 Differences

There 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 1 was entirely hand-coded, where as version 2 resource interfaces are generated from a model. Version 2 resource interfaces are significantly more consistent. Some of the systemic differences include:

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

# version 1 s3 = AWS::S3.new

# version 2

s3 = Aws::S3::Resource.new

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

# version 1

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

(23)

# version 2

s3.bucket('bucket-name').object('key').delete

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

Debugging Tip: Getting Wire Trace Information from a Client

You can get wire trace information from an AWS client when you create it by setting the

http_wire_trace option. This information helps differentiate client changes, service issues, and user errors. The following example creates an Amazon S3 client with wire tracing enabled.

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

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

require 'aws-sdk'

s3 = Aws::S3::Resource.new(client: Aws::S3::Client.new(http_wire_trace: true)) if s3.bucket(ARGV[0]).exists?

puts "Bucket #{ARGV[0]} exists"

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

end

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

opening connection to bucket_name.s3-us-west-1.amazonaws.com:443...

opened

starting SSL for bucket_name.s3-us-west-1.amazonaws.com:443...

SSL established

<- "HEAD / HTTP/1.1\r\n Content-Type: \r\n Accept-Encoding: \r\n

User-Agent: aws-sdk-ruby2/2.2.7 ruby/2.1.7 x64-mingw32\r\n X-Amz-Date: 20160121T191751Z\r\n

Host: bucket_name.s3-us-west-1.amazonaws.com\r\n

X-Amz-Content-Sha256: e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855\r

\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"

(24)

-> "Content-Type: application/xml\r\n"

-> "Transfer-Encoding: chunked\r\n"

-> "Date: Thu, 21 Jan 2016 19:17:54 GMT\r\n"

-> "Server: AmazonS3\r\n"

-> "\r\n"

Conn keep-alive

Bucket bucket_name exists

Stubbing Client Responses and Errors

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

Stubbing Client Responses

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

• Lists as empty arrays

• Maps as empty hashes

• Numeric values as zero

• Dates as now

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

require 'aws-sdk'

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

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

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

# List each bucket by name bucket_names.each do |name|

puts name end

Running this code displays the following.

aws-sdk aws-sdk2

Note

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

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

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

(25)

The AWS SDK for Ruby raises two ArgumentError exceptions.

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

Stubbing Client Errors

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

require 'aws-sdk'

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

s3.head_bucket({bucket: 'aws-sdk'}) rescue Exception => ex

puts "Caught #{ex.class} error calling 'head_bucket' on 'aws-sdk'"

end

Paging Response Data

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

Paged Responses Are Enumerable

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

s3 = Aws::S3::Client.new

s3.list_objects(bucket:'aws-sdk').each do |response|

puts response.contents.map(&:key) end

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

Handling Paged Responses Manually

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

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

s3 = Aws::S3::Client.new

# Get the first page of data

response = s3.list_objects(bucket:'aws-sdk')

# Get additional pages

(26)

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

end

Note

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

Paged Data Classes

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

Using Waiters

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

Invoking a Waiter

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

ec2 = Aws::EC2::Client.new begin

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

rescue Aws::Waiters::Errors::WaiterFailed => error

puts "failed waiting for instance running: #{error.message}"

end

The first parameter is the waiter name, which is specific to the service client and indicates which

operation is being waited for. The second parameter is a hash of parameters that are passed to the client method called by the waiter, which varies according to the waiter name.

For a list of operations that can be waited for and the client methods called for each operation, see the

#waiter_names and #wait_until field documentation for the client you are using.

Wait Failures

Waiters can fail with any of the following exceptions.

Aws::Waiters::Errors::FailureStateError

A failure state was encountered while waiting.

Aws::Waiters::Errors::NoSuchWaiterError

The specified waiter name is not defined for the client being used.

Aws::Waiters::Errors::TooManyAttemptsError

The number of attempts exceeded the waiter’s max_attempts value.

(27)

Aws::Waiters::Errors::UnexpectedError

An unexpected error occurred while waiting.

Aws::Waiters::Errors::WaiterFailed

One of the wait states was exceeded or another failure occurred while waiting.

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

rescue Aws::Waiters::Errors::WaiterFailed => error

puts "failed waiting for instance running: #{error.message}"

end

Configuring a Waiter

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

# Poll for ~25 seconds client.wait_until(...) do |w|

w.max_attempts = 5 w.delay = 5

end

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

Extending a Waiter

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

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

ec2 = Aws::EC2::Client.new

ec2.wait_until(:instance_running, instance_ids:['i-12345678']) do |w|

w.interval = 0 # disable normal sleep w.before_wait do |n, resp|

sleep(n ** 2) end

end

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

started_at = Time.now

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

(28)

end end

Specifying a Client Timeout Duration

By default, the AWS SDK for Ruby performs up to three retries, with 15 seconds between retries, for a total 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 five seconds between two retries on every client operation. Therefore, Amazon S3 client operations could take up to 15 seconds to time out.

s3 = Aws::S3::Client.new(

region: region, retry_limit: 2,

retry_backoff: lambda { |c| sleep(5) } )

(29)

AWS SDK for Ruby Code Examples

This 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 repository on 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 and use cases, versus simple code snippets that cover only individual API calls. For instructions, see the Proposing new code examples section in the Readme on GitHub.

Topics

• CloudTrail Examples Using the AWS SDK for Ruby (p. 23)

• Amazon CloudWatch Examples Using the AWS SDK for Ruby (p. 28)

• CodeBuild Examples Using the AWS SDK for Ruby (p. 50)

• Amazon DynamoDB Examples Using the AWS SDK for Ruby (p. 52)

• Amazon EC2 Examples Using the AWS SDK for Ruby (p. 63)

• AWS Elastic Beanstalk Examples Using the AWS SDK for Ruby (p. 100)

• AWS Identity and Access Management (IAM) Examples Using the AWS SDK for Ruby (p. 102)

• AWS Key Management Service Examples Using the AWS SDK for Ruby (p. 126)

• AWS Lambda Examples Using the AWS SDK for Ruby (p. 129)

• Amazon Polly Examples Using the AWS SDK for Ruby (p. 133)

• Amazon RDS Examples Using the AWS SDK for Ruby (p. 136)

• Amazon S3 Examples Using the AWS SDK for Ruby (p. 141)

• Amazon SES Examples Using the AWS SDK for Ruby (p. 182)

• Amazon SNS Examples Using the AWS SDK for Ruby (p. 186)

• Amazon SQS Examples Using the AWS SDK for Ruby (p. 189)

• Amazon WorkDocs Examples (p. 208)

CloudTrail Examples Using the AWS SDK for Ruby

CloudTrail is an AWS service that you can use to monitor your AWS deployments in the cloud by getting a history of AWS API calls for your account. You can use the following AWS SDK for Ruby code examples to access AWS CloudTrail. For more information about CloudTrail, see the AWS CloudTrail;

documentation.

Topics

• Listing the CloudTrail Trails (p. 23)

• Creating a CloudTrail Trail (p. 24)

• Listing CloudTrail Trail Events (p. 26)

• Deleting a CloudTrail Trail (p. 27)

Listing the CloudTrail Trails

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

Choose Copy to save the code locally.

(30)

Create the file describe_trails.rb with the following code.

# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.

## This file is licensed under the Apache License, Version 2.0 (the "License").

# You may not use this file except in compliance with the License. A copy of the

# License is located at

## http://aws.amazon.com/apache2.0/

#

# This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS

# OF ANY KIND, either express or implied. See the License for the specific

# language governing permissions and limitations under the License.

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

# Create client in us-west-2

client = Aws::CloudTrail::Client.new(region: 'us-west-2') resp = client.describe_trails({})

puts

puts "Found #{resp.trail_list.count} trail(s) in us-west-2:"

puts

resp.trail_list.each do |trail|

puts 'Name: ' + trail.name

puts 'S3 bucket name: ' + trail.s3_bucket_name puts

end

See the complete example on GitHub.

Creating a CloudTrail Trail

This example uses the create_trail method to create a CloudTrail trail in the us-west-2 region. It requires two inputs, the name of the trail and the name of the bucket in which CloudTrail stores

information. If the bucket does not have the proper policy, include the -p flag to attach the correct policy to the bucket.

Choose Copy to save the code locally.

# Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.

## This file is licensed under the Apache License, Version 2.0 (the "License").

# You may not use this file except in compliance with the License. A copy of the

# License is located at

#

# http://aws.amazon.com/apache2.0/

## This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS

# OF ANY KIND, either express or implied. See the License for the specific

# language governing permissions and limitations under the License.

require 'aws-sdk-cloudtrail' # v2: require 'aws-sdk' require 'aws-sdk-s3'

require 'aws-sdk-sts'

# Attach IAM policy to bucket def add_policy(bucket) # Get account ID using STS

sts_client = Aws::STS::Client.new(region: 'us-west-2') resp = sts_client.get_caller_identity({})

(31)

account_id = resp.account # Attach policy to S3 bucket

s3_client = Aws::S3::Client.new(region: 'us-west-2') begin

policy = {

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

{

'Sid' => 'AWSCloudTrailAclCheck20150319', 'Effect' => 'Allow',

'Principal' => {

'Service' => 'cloudtrail.amazonaws.com', },

'Action' => 's3:GetBucketAcl',

'Resource' => 'arn:aws:s3:::' + bucket, },

{

'Sid' => 'AWSCloudTrailWrite20150319', 'Effect' => 'Allow',

'Principal' => {

'Service' => 'cloudtrail.amazonaws.com', },

'Action' => 's3:PutObject',

'Resource' => 'arn:aws:s3:::' + bucket + '/AWSLogs/' + account_id + '/*', 'Condition' => {

'StringEquals' => {

's3:x-amz-acl' => 'bucket-owner-full-control', },

}, }, ] }.to_json

s3_client.put_bucket_policy(

bucket: bucket, policy: policy )

puts 'Successfully added policy to bucket ' + bucket rescue StandardError => err

puts 'Got error trying to add policy to bucket ' + bucket + ':' puts err

exit 1 end end

# main name = '' bucket = ''

attach_policy = false i = 0

while i < ARGV.length case ARGV[i]

when '-b' i += 1

bucket = ARGV[i]

when '-p'

attach_policy = true else

name = ARGV[i]

(32)

end i += 1 end

if name == '' || bucket == ''

puts 'You must supply a trail name and bucket name' puts USAGE

exit 1 end

if attach_policy add_policy(bucket) end

# Create client in us-west-2

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

client.create_trail({

name: name, # required

s3_bucket_name: bucket, # required })

puts 'Successfully created CloudTrail ' + name + ' in us-west-2' rescue StandardError => err

puts 'Got error trying to create trail ' + name + ':' puts err

exit 1 end

See the complete example on GitHub.

Listing CloudTrail Trail Events

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

# Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.

## This file is licensed under the Apache License, Version 2.0 (the "License").

# You may not use this file except in compliance with the License. A copy of the

# License is located at

## http://aws.amazon.com/apache2.0/

#

# This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS

# OF ANY KIND, either express or implied. See the License for the specific

# language governing permissions and limitations under the License.

require 'aws-sdk-cloudtrail' # v2: require 'aws-sdk' def show_event(event)

puts 'Event name: ' + event.event_name puts 'Event ID: ' + event.event_id puts "Event time: #{event.event_time}"

puts 'User name: ' + event.username puts 'Resources:'

event.resources.each do |r|

puts ' Name: ' + r.resource_name puts ' Type: ' + r.resource_type

(33)

puts '' end end

# Create client in us-west-2

client = Aws::CloudTrail::Client.new(region: 'us-west-2') resp = client.lookup_events()

putsputs "Found #{resp.events.count} events in us-west-2:"

puts

resp.events.each do |e|

show_event(e) end

See the complete example on GitHub.

Deleting a CloudTrail Trail

This example uses the delete_trail method to delete a CloudTrail trail in the us-west-2 region. It requires one input, the name of the trail.

Choose Copy to save the code locally.

# Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.

#

# This file is licensed under the Apache License, Version 2.0 (the "License").

# You may not use this file except in compliance with the License. A copy of the

# License is located at

## http://aws.amazon.com/apache2.0/

## This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS

# OF ANY KIND, either express or implied. See the License for the specific

# language governing permissions and limitations under the License.

require 'aws-sdk-cloudtrail' # v2: require 'aws-sdk' if ARGV.length != 1

puts 'You must supply the name of the trail to delete' exit 1

end

name = ARGV[0]

# Create client in us-west-2

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

client.delete_trail({

name: name, # required })

puts 'Successfully deleted CloudTrail ' + name + ' in us-west-2' rescue StandardError => err

puts 'Got error trying to delete trail ' + name + ':' puts err

exit 1 end

See the complete example on GitHub.

(34)

Amazon CloudWatch Examples Using the AWS SDK for Ruby

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

Topics

• Getting Information about Amazon CloudWatch Alarms (p. 28)

• Creating an Amazon CloudWatch Alarm (p. 29)

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

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

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

Getting Information about Amazon CloudWatch Alarms

The following code example displays information about available metric alarms in Amazon CloudWatch.

# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.

# SPDX-License-Identifier: Apache-2.0 require 'aws-sdk-cloudwatch'

# Displays information about available metric alarms in Amazon CloudWatch.

#

# @param cloudwatch_client [Aws::CloudWatch::Client]

# An initialized CloudWatch client.

# @example

# describe_metric_alarms(Aws::CloudWatch::Client.new(region: 'us-east-1')) def describe_metric_alarms(cloudwatch_client)

response = cloudwatch_client.describe_alarms if response.metric_alarms.count.positive?

response.metric_alarms.each do |alarm|

puts '-' * 16

puts 'Name: ' + alarm.alarm_name puts 'State value: ' + alarm.state_value puts 'State reason: ' + alarm.state_reason puts 'Metric: ' + alarm.metric_name puts 'Namespace: ' + alarm.namespace puts 'Statistic: ' + alarm.statistic 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

if alarm.key?(:ok_actions) && alarm.ok_actions.count.positive?

puts 'OK actions:'

alarm.ok_actions.each do |a|

puts ' ' + a end

end

if alarm.key?(:alarm_actions) && alarm.alarm_actions.count.positive?

(35)

puts 'Alarm actions:'

alarm.alarm_actions.each do |a|

puts ' ' + a end

end

if alarm.key?(:insufficient_data_actions) &&

alarm.insufficient_data_actions.count.positive?

puts 'Insufficient data actions:'

alarm.insufficient_data_actions.each do |a|

puts ' ' + a end

end

puts 'Dimensions:'

if alarm.key?(:dimensions) && alarm.dimensions.count.positive?

alarm.dimensions.each do |d|

puts ' Name: ' + d.name + ', Value: ' + d.value end

else

puts ' None for this alarm.' end

end else

puts 'No alarms found.' end

rescue StandardError => e

puts "Error getting information about alarms: #{e.message}"

end

# Full example call:

def run_me region = ''

# Print usage information and then stop.

if ARGV[0] == '--help' || ARGV[0] == '-h'

puts 'Usage: ruby cw-ruby-example-show-alarms.rb REGION' puts 'Example: ruby cw-ruby-example-show-alarms.rb us-east-1' exit 1

# If no values are specified at the command prompt, use these default values.

elsif ARGV.count.zero?

region = 'us-east-1'

# Otherwise, use the values as specified at the command prompt.

else

region = ARGV[0]

end

cloudwatch_client = Aws::CloudWatch::Client.new(region: region) puts 'Available alarms:'

describe_metric_alarms(cloudwatch_client) end

run_me if $PROGRAM_NAME == __FILE__

Creating an Amazon CloudWatch Alarm

The following code example creates a new CloudWatch alarm (or updates an existing alarm, if an alarm with the specified name already exists).

# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.

# SPDX-License-Identifier: Apache-2.0 require 'aws-sdk-cloudwatch'

(36)

# Creates or updates an alarm in Amazon CloudWatch.

## @param cloudwatch_client [Aws::CloudWatch::Client]

# An initialized CloudWatch client.

# @param alarm_name [String] The name of the alarm.

# @param alarm_description [String] A description about the alarm.

# @param metric_name [String] The name of the metric associated with the alarm.

# @param alarm_actions [Array] A list of Strings representing the

# Amazon Resource Names (ARNs) to execute when the alarm transitions to the

# ALARM state.

# @param namespace [String] The namespace for the metric to alarm on.

# @param statistic [String] The statistic for the metric.

# @param dimensions [Array] A list of dimensions for the metric, specified as

# Aws::CloudWatch::Types::Dimension.

# @param period [Integer] The number of seconds before re-evaluating the metric.

# @param unit [String] The unit of measure for the statistic.

# @param evaluation_periods [Integer] The number of periods over which data is

# compared to the specified threshold.

# @param theshold [Float] The value against which the specified statistic is compared.

# @param comparison_operator [String] The arithmetic operation to use when

# comparing the specified statistic and threshold.

# @return [Boolean] true if the alarm was created or updated; otherwise, false.

# @example

# exit 1 unless alarm_created_or_updated?(

# Aws::CloudWatch::Client.new(region: 'us-east-1'),

# 'ObjectsInBucket',

# 'Objects exist in this bucket for more than 1 day.',

# 'NumberOfObjects',

# ['arn:aws:sns:us-east-1:111111111111:Default_CloudWatch_Alarms_Topic'],

# 'AWS/S3',

# 'Average',

# [

# {

# name: 'BucketName',

# value: 'doc-example-bucket'

# },

# {

# name: 'StorageType',

# value: 'AllStorageTypes'

# }

# ],

# 86_400,

# 'Count',

# 1,

# 1,

# 'GreaterThanThreshold'

# )

def alarm_created_or_updated?(

cloudwatch_client, alarm_name,

alarm_description, metric_name, alarm_actions, namespace, statistic, dimensions, period, unit,

evaluation_periods, threshold,

comparison_operator

) cloudwatch_client.put_metric_alarm(

alarm_name: alarm_name,

alarm_description: alarm_description,

(37)

metric_name: metric_name, alarm_actions: alarm_actions, namespace: namespace,

statistic: statistic, dimensions: dimensions, period: period,

unit: unit,

evaluation_periods: evaluation_periods, threshold: threshold,

comparison_operator: comparison_operator )

return true

rescue StandardError => e

puts "Error creating alarm: #{e.message}"

return false end

# Full example call:

def run_me

alarm_name = 'ObjectsInBucket'

alarm_description = 'Objects exist in this bucket for more than 1 day.' metric_name = 'NumberOfObjects'

# Notify this Amazon Simple Notification Service (Amazon SNS) topic when # the alarm transitions to the ALARM state.

alarm_actions = ['arn:aws:sns:us-east-1:111111111111:Default_CloudWatch_Alarms_Topic']

namespace = 'AWS/S3' statistic = 'Average' dimensions = [ {

name: 'BucketName',

value: 'doc-example-bucket' },

{

name: 'StorageType', value: 'AllStorageTypes' }

] period = 86_400 # 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.

region = 'us-east-1'

cloudwatch_client = Aws::CloudWatch::Client.new(region: region) if alarm_created_or_updated?(

cloudwatch_client, alarm_name, alarm_description, metric_name, alarm_actions, namespace, statistic, dimensions, period, unit,

evaluation_periods, threshold,

comparison_operator )

puts "Alarm '#{alarm_name}' created or updated."

else

puts "Could not create or update alarm '#{alarm_name}'."

end end

參考文獻

相關文件

Let us emancipate the student, and give him time and opportunity for the cultivation of his mind, so that in his pupilage he shall not be a puppet in the hands of others, but rather

The format of the URI in the first line of the header is not specified. For example, it could be empty, a single slash, if the server is only handling XML-RPC calls. However, if the

Because the influence of organizational citizenship behavior on job evaluation is not often investigated in the filed of human resource management and organizational behavior,

This discovery is not only to provide a precious resource for the research of Wenxuan that has a long and excellent tradition in Chinese literature studies, but also to stress

Under the pressure of the modern era is often busy with work and financial resources, and sometimes not in fact do not want to clean up the environment, but in a full day of hard

This is especially important if the play incorporates the use of (a) flashbacks to an earlier time in the history of the characters (not the main focus of the play, but perhaps the

To be an effective practitioner, a defined body of formal knowledge and skills is the necessary, but not sufficient, condition to meet workplace requirements. The important

Because both sets R m  and L h i ði ¼ 1; 2; :::; JÞÞ are second-order regular, similar to [19, Theorem 3.86], we state in the following theorem that there is no gap between