Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

webzerg/aws-sdk-ruby

Repository files navigation

AWS SDK for Ruby - Version 2

![Gitter](https://badges.gitter.im/Join Chat.svg) Build Status Code Climate Coverage Status Dependency Status

This is version 2 of the aws-sdk gem. Version 1 can be found in the aws-sdk-v1 branch.

Links of Interest

NameError: uninitialized constant AWS

If you receive this error, you likely have upgraded to version 2 of the aws-sdk gem unintentionally. Version 2 uses the Aws namespace, not AWS. This allows version 1 and version 2 to be used in the same application.

Installation

The AWS SDK for Ruby is available as the aws-sdk gem from RubyGems. Please use a major version when expressing a dependency on aws-sdk.

gem 'aws-sdk', '~> 2'

Configuration

You need to configure :credentials and a :region to make API calls. It is recommended that you provide these via your environment. This makes it easier to rotate credentials and it keeps your secrets out of source control.

The SDK searches the following locations for credentials:

  • ENV['AWS_ACCESS_KEY_ID'] and ENV['AWS_SECRET_ACCESS_KEY']
  • Unless ENV['AWS_SDK_CONFIG_OPT_OUT'] is set, the shared configuration files (~/.aws/credentials and ~/.aws/config) will be checked for a role_arn and source_profile, which if present will be used to attempt to assume a role.
  • The shared credentials ini file at ~/.aws/credentials (more information)
    • Unless ENV['AWS_SDK_CONFIG_OPT_OUT'] is set, the shared configuration ini file at ~/.aws/config will also be parsed for credentials.
  • From an instance profile when running on EC2, or from the ECS credential provider when running in an ECS container with that feature enabled.

The SDK searches the following locations for a region:

  • ENV['AWS_REGION']
  • Unless ENV['AWS_SDK_CONFIG_OPT_OUT'] is set, the shared configuration files (~/.aws/credentials and ~/.aws/config) will also be checked for a region selection.

The region is used to construct an SSL endpoint. If you need to connect to a non-standard endpoint, you may specify the :endpoint option.

Configuration Options

You can configure default credentials and region via Aws.config. In version 2, Aws.config is a vanilla Ruby hash, not a method like it was in version 1. The Aws.config hash takes precedence over environment variables.

require 'aws-sdk'
Aws.config.update({
 region: 'us-west-2',
 credentials: Aws::Credentials.new('akid', 'secret')
})

Valid region and credentials options are:

You may also pass configuration options directly to resource and client constructors. These options take precedence over the environment and Aws.config defaults.

# resource constructors
ec2 = Aws::EC2::Resource.new(region:'us-west-2', credentials: credentials)
# client constructors
ec2 = Aws::EC2::Client.new(region:'us-west-2', credentials: credentials)

Please take care to never commit credentials to source control. We strongly recommended loading credentials from an external source.

require 'aws-sdk'
require 'json'
creds = JSON.load(File.read('secrets.json'))
Aws.config[:credentials] = Aws::Credentials.new(creds['AccessKeyId'], creds['SecretAccessKey'])

API Clients (aws-sdk-core gem)

Construct a service client to make API calls. Each client provides a 1-to-1 mapping of methods to API operations. Refer to the API documentation for a complete list of available methods.

# list buckets in Amazon S3
s3 = Aws::S3::Client.new
resp = s3.list_buckets
resp.buckets.map(&:name)
#=> ["bucket-1", "bucket-2", ...]

API methods accept a hash of additional request parameters and return structured response data.

# list the first two objects in a bucket
resp = s3.list_objects(bucket: 'aws-sdk-core', max_keys: 2)
resp.contents.each do |object|
 puts "#{object.key} => #{object.etag}"
end

Paging Responses

Many AWS operations limit the number of results returned with each response. To make it easy to get the next page of results, every AWS response object is enumerable:

# yields one response object per API call made, this will enumerate
# EVERY object in the named bucket
s3.list_objects(bucket:'aws-sdk').each do |response|
 puts response.contents.map(&:key)
end

If you prefer to control paging yourself, response objects have helper methods that control paging:

# make a request that returns a truncated response
resp = s3.list_objects(bucket:'aws-sdk')
resp.last_page? #=> false
resp.next_page? #=> true
resp = resp.next_page # send a request for the next response page
resp = resp.next_page until resp.last_page?

Waiters

Waiters are utility methods that poll for a particular state. To invoke a waiter, call #wait_until on a client:

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

Waiters have sensible default polling intervals and maximum attempts. You can configure these per call to #wait_until. You can also register callbacks that are triggered before each polling attempt and before waiting. See the API documentation for more examples and for a list of supported waiters per service.

Resource Interfaces (aws-sdk-resources gem)

Resource interfaces are object oriented classes that represent actual resources in AWS. Resource interfaces built on top of API clients and provide additional functionality.

s3 = Aws::S3::Resource.new
# reference an existing bucket by name
bucket = s3.bucket('aws-sdk')
# enumerate every object in a bucket
bucket.objects.each do |obj|
 puts "#{obj.key} => #{obj.etag}"
end
# batch operations, delete objects in batches of 1k
bucket.objects(prefix: '/tmp-files/').delete
# single object operations
obj = bucket.object('hello')
obj.put(body:'Hello World!')
obj.etag
obj.delete

REPL - AWS Interactive Console

The aws-sdk-core gem ships with a REPL that provides a simple way to test the Ruby SDK. You can access the REPL by running aws.rb from the command line.

$ aws.rb
Aws> ec2.describe_instances.reservations.first.instances.first
[Aws::EC2::Client 200 0.216615 0 retries] describe_instances()
<struct
 instance_id="i-1234567",
 image_id="ami-7654321",
 state=<struct code=16, name="running">,
 ...>

You can enable HTTP wire logging by setting the verbose flag:

$ aws.rb -v

In the REPL, every service class has a helper that returns a new client object. Simply downcase the service module name for the helper:

  • Aws::S3 => s3
  • Aws::EC2 => ec2
  • etc

Versioning

This project uses semantic versioning. You can safely express a dependency on a major version and expect all minor and patch versions to be backwards compatible.

Supported Services

Service Name Service Class API Version
AWS Application Discovery Service ApplicationDiscoveryService 2015年11月01日
AWS Certificate Manager ACM 2015年12月08日
AWS CloudFormation CloudFormation 2010年05月15日
AWS CloudTrail CloudTrail 2013年11月01日
AWS CodeCommit CodeCommit 2015年04月13日
AWS CodeDeploy CodeDeploy 2014年10月06日
AWS CodePipeline CodePipeline 2015年07月09日
AWS Config ConfigService 2014年11月12日
AWS Data Pipeline DataPipeline 2012年10月29日
AWS Database Migration Service DatabaseMigrationService 2016年01月01日
AWS Device Farm DeviceFarm 2015年06月23日
AWS Direct Connect DirectConnect 2012年10月25日
AWS Directory Service DirectoryService 2015年04月16日
AWS Elastic Beanstalk ElasticBeanstalk 2010年12月01日
AWS Identity and Access Management IAM 2010年05月08日
AWS Import/Export ImportExport 2010年06月01日
AWS IoT IoT 2015年05月28日
AWS IoT Data Plane IoTDataPlane 2015年05月28日
AWS Key Management Service KMS 2014年11月01日
AWS Lambda Lambda 2015年03月31日
AWS Lambda LambdaPreview 2014年11月11日
AWS Marketplace Commerce Analytics MarketplaceCommerceAnalytics 2015年07月01日
AWS OpsWorks OpsWorks 2013年02月18日
AWS Security Token Service STS 2011年06月15日
AWS Service Catalog ServiceCatalog 2015年12月10日
AWS Storage Gateway StorageGateway 2013年06月30日
AWS Support Support 2013年04月15日
AWS WAF WAF 2015年08月24日
AWSMarketplace Metering MarketplaceMetering 2016年01月14日
Amazon API Gateway APIGateway 2015年07月09日
Amazon CloudFront CloudFront 2016年09月07日
Amazon CloudHSM CloudHSM 2014年05月30日
Amazon CloudSearch CloudSearch 2013年01月01日
Amazon CloudSearch Domain CloudSearchDomain 2013年01月01日
Amazon CloudWatch CloudWatch 2010年08月01日
Amazon CloudWatch Events CloudWatchEvents 2015年10月07日
Amazon CloudWatch Logs CloudWatchLogs 2014年03月28日
Amazon Cognito Identity CognitoIdentity 2014年06月30日
Amazon Cognito Identity Provider CognitoIdentityProvider 2016年04月18日
Amazon Cognito Sync CognitoSync 2014年06月30日
Amazon DynamoDB DynamoDB 2012年08月10日
Amazon DynamoDB Streams DynamoDBStreams 2012年08月10日
Amazon EC2 Container Registry ECR 2015年09月21日
Amazon EC2 Container Service ECS 2014年11月13日
Amazon ElastiCache ElastiCache 2015年02月02日
Amazon Elastic Compute Cloud EC2 2016年09月15日
Amazon Elastic File System EFS 2015年02月01日
Amazon Elastic MapReduce EMR 2009年03月31日
Amazon Elastic Transcoder ElasticTranscoder 2012年09月25日
Amazon Elasticsearch Service ElasticsearchService 2015年01月01日
Amazon GameLift GameLift 2015年10月01日
Amazon Glacier Glacier 2012年06月01日
Amazon Import/Export Snowball Snowball 2016年06月30日
Amazon Inspector Inspector 2016年02月16日
Amazon Kinesis Kinesis 2013年12月02日
Amazon Kinesis Analytics KinesisAnalytics 2015年08月14日
Amazon Kinesis Firehose Firehose 2015年08月04日
Amazon Machine Learning MachineLearning 2014年12月12日
Amazon Redshift Redshift 2012年12月01日
Amazon Relational Database Service RDS 2014年10月31日
Amazon Route 53 Route53 2013年04月01日
Amazon Route 53 Domains Route53Domains 2014年05月15日
Amazon Simple Email Service SES 2010年12月01日
Amazon Simple Notification Service SNS 2010年03月31日
Amazon Simple Queue Service SQS 2012年11月05日
Amazon Simple Storage Service S3 2006年03月01日
Amazon Simple Systems Management Service SSM 2014年11月06日
Amazon Simple Workflow Service SWF 2012年01月25日
Amazon SimpleDB SimpleDB 2009年04月15日
Amazon WorkSpaces WorkSpaces 2015年04月08日
Application Auto Scaling ApplicationAutoScaling 2016年02月06日
Auto Scaling AutoScaling 2011年01月01日
Elastic Load Balancing ElasticLoadBalancing 2012年06月01日
Elastic Load Balancing ElasticLoadBalancingV2 2015年12月01日

License

This library is distributed under the Apache License, version 2.0

copyright 2013. amazon web services, inc. all rights reserved.
licensed under the apache license, version 2.0 (the "license");
you may not use this file except in compliance with the license.
you may obtain a copy of the license at
 http://www.apache.org/licenses/license-2.0
unless required by applicable law or agreed to in writing, software
distributed under the license 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.

About

The official AWS SDK for Ruby.

Resources

License

Contributing

Stars

Watchers

Forks

Packages

Contributors

Languages

  • Ruby 97.0%
  • Gherkin 2.7%
  • Other 0.3%

AltStyle によって変換されたページ (->オリジナル) /