re:generate AWS マイスターシリーズ AWS SDK for PHP & AWS SDK for Ruby & boto(python) & JavaScript in Node.js 2013.12.20 アマゾンデータサービスジャパン株式会社 ソリューションアーキテクト 今井榎並蒋 2012 Amazon.com, Inc. and its affiliates. All rights reserved. May not be copied, modified or distributed in whole or in part without the express consent of Amazon.com, Inc.
ウェビナー (Web セミナー ) へようこそ!! 参加者は 自動的にミュートになっています! 質問を投げることができます! GoToWebinar の仕組みを使って 書き込んでください ただし環境によっては 日本語の直接 入 力力ができないので お 手数ですが テキストエディタ等に打ち込んでから コピペしてください 最後の Q&A の時間で できるだけ回答させて頂きます 書き込んだ質問は 主催者にしか 見見えません! Twitter のハッシュタグは #jawsug でどうぞ 2 2012 Amazon.com, Inc. and its affiliates. All rights reserved. May not be copied, modified or distributed in whole or in part without the express consent of Amazon.com, Inc.
Web セミナー 週刊 AWS マイスターシリーズ re:generate!! AWS マイスターシリーズ 12 月4 日 AWS re:invent アップデート振り返り 12 月11 日 AWS SDK for Java/.Net 申し込みサイト http://aws.amazon.com/jp/event_ schedule/ 過去資料料集 http://aws.amazon.com/jp/aws- meister/ 3
Agenda! AWS SDK 概要! AWS SDK for PHP! boto(python)! AWS SDK for Ruby! AWS SDK for JavaScript in Node.js! まとめ 4
AWS SDK 概要
AWS SDK の重要性! AWS はプログラマブルなインフラ プログラムから扱うためには SDK が必要 ほぼすべてのサービスはマネジメントコンソールから利利 用できるが 自動化しようと思ったらプログラムから扱うのが必須 自動化すると AWS は何倍も便便利利になる! 代表的な 用途 インフラ構築 / 運 用の 自動化 EC2 や RDS を上げたり下げたり CloudFormation でスタックをデプロイしたり アプリケーション的なサービスの利利 用 S3 にデータをアップしたり DynamoDB や SQS にデータ 入れたり出したり
AWS SDK! AWS のサービスは HTTP/HTTPS で REST/SOAP 形式の API をサポート 例例えば EC2 : Start/Stop/Terminate S3 : GetObject/PutObject DynamoDB : Get/Put! SDK はこれらの API を抽象化し 各 言語からの利利 用を 非常に簡単にしてくれる Your code AWS SDK API 7 EC2 S3 その他サービス
AWS SDK! 下記の 言語 / 環境で提供中 Java Python PHP.NET Ruby JavaScript in nodejs JavaScript in the Browser ios Android
AWS SDK! 今回は下記についてお話します Java Python PHP.NET Ruby JavaScript in Node.js JavaScript in the Browser ios Android
AWS SDK の使い 方! 必要な 言語の SDK をインストール 言語ごとにインストール 方法が異異なります このあとの章で 言語ごとに解説します! Credential(AWS API の認証情報 ) を 用意する! ファクトリーメソッドを利利 用してサービス ( 例例えば S3) のクライアントオブジェクトを 生成 このときに Credential を渡す! クライアントオブジェクトのメソッドを使ってオペレーション ( 例例えば PutObject)! 言語によってはより 高度度に抽象化されている SDK もあります
Credential の取り扱い! Credential の取り扱いについてはいくつかのやり 方がありますが IAM Role もしくは環境変数を使うのがオススメです PHP を例例にそれぞれの実装 方法をご案内します! コード内に直接埋め込むパターン ( コード内に Credential が 入り込んでしまうのでやっちゃダメなパターン ) <?php $s3client = S3Client::factory(array( 'key' => 'your- aws- access- key- id', 'secretʻ => 'your- aws- secret- access- key', ));
Credential の取り扱い! config ファイルで Credential を設定するパターン PHP と boto ではこの 方法が提供されている これも Credential がファイル化されるので良良くないパターン $ vim aws- config.php <?php return array( 'includes' => array('_ aws'), 'services' => array( 'default_ settings' => array( 'params' => array( 'key' => 'your- access- key- id', 'secret' => 'your- secret- access- key',) ) ) ); $ vim sample.php <?php $aws = Aws::factory(ʻ aws- config.php'); $s3client = $aws- >get('s3');
Credential の取り扱い! 環境変数で Credential を設定するパターン AWS_ ACCESS_ KEY_ ID, AWS_ SECRET_ KEY という環境変数を実 行行ユーザーで設定しておくことによってコードから Credential を追い出せる $ export AWS_ ACCESS_ KEY_ ID="your- aws- access- key- id" $ export AWS_ SECRET_ KEY="your- aws- secret- access- key $vim sample.php <?php $s3client = S3Client::factory();
Credential の取り扱い! IAM Role で Credential を設定するパターン コードが動くのが EC2 上であれば IAM Role を使うことによって EC2 自体に AWS API へのアクセス権限を付与できる よってコードや環境変数に Credential を持たせずに済む 例例えば S3 フルアクセスの権限を持った IAM Role を作成して EC2 にその Role を 割り当てると
Credential の取り扱い! IAM Role で Credential を設定するパターン 前のページのように S3 アクセス権限を持った Role を EC2 に割り当てると 下記を書くだけで利利 用可能 $vim sample.php <?php $s3client = S3Client::factory(); これは SDK が内部で STS(Security Token Service) を利利 用しており AccessKey,SecretAccessKey,Token を 自動的に
AWS SDK for PHP
AWS SDK for PHP! Amazon 提供の AWS 開発 用の PHP 向け SDK! 現在は Version2! http://aws.amazon.com/jp/sdkforphp/! 環境 :PHP5.3.3 以降降! Guzzle HTTP Client framework 上で構築されている! 依存 Extension curl
操作可能サービス Direct Connect Elasticache IAM EC2 SimpleDB OpsWorks ELB S3 Elastic Transcoder Auto Scaling Glacier SQS EMR CloudFront SNS Route53 Storage Gateway SES VPC Import/Export SWF DynamoDB Elastic Beanstalk CloudSearch RDS Cloud Formation Redshift Cloud Watch
利利 用 方法! Composer によるインストール ( 推奨 ) http://docs.aws.amazon.com/aws- sdk- php/guide/latest/ installation.html#installing- via- composer! Phar よるインストール http://docs.aws.amazon.com/aws- sdk- php/guide/latest/ installation.html#installing- via- phar! Zip ファイルからインストール http://docs.aws.amazon.com/aws- sdk- php/guide/latest/ installation.html#installing- via- zip! PEAR によるインストール http://docs.aws.amazon.com/aws- sdk- php/guide/latest/ installation.html#installing- via- pear
初期設定! インストール 方法により以下のとおり異異なります インストール方法 Composer Phar Zip PEAR インクルード require '/path/to/vendor/autoload.php'; require '/path/to/aws.phar'; require '/path/to/aws-autoloader.php'; 'AWSSDKforPHP/aws.phar';! コンフィグレーションファイルの設定 クレデンシャル情報などを設定可能 factory() の引数として指定することも可能 ʻ src/aws/common/resources/aws- config.phpʼ を参考に追加
サンプル :S3 - putobject API 仕様 : http://docs.aws.amazon.com/aws- sdk- php/latest/class- Aws.S3.S3Client.html#_ putobject <?php require '/path/to/vendor/autoload.php'; use Aws\Common\Aws; use Aws\S3\Exception\S3Exception; try { $client = S3Client::factory; $bucket = ʼ your_ bucket'; $file = 'test.txt'; 1 $result = $client- >putobject(array( 'Bucket' => $bucket, 'Key' => $file, 'Body' => fopen($file, 'r'), )); // 結果表 示 var_ dump($result); } catch (S3Exception $e) { echo '*** Error ***'. "\n"; echo $e- >getmessage(); } 2 1 S3 クライアント作成 2 putobject 実 行行 Bucket を指定 Key は ファイル名 Body にアップロードするファイルストリームを指定 (*) 事前に Bucket が作成されている必要があります
サンプル :S3 - getobject API 仕様 : http://docs.aws.amazon.com/aws- sdk- php/latest/class- Aws.S3.S3Client.html#_ getobject <?php require '/path/to/vendor/autoload.php'; use Aws\Common\Aws; use Aws\S3\Exception\S3Exception; try { $client = S3Client::factory;1 $bucket = ʼ your_ bucket'; $file = 'test.txt'; $result = $client- >getobject(array( 'Bucket' => $bucket, 'Key' => $file, )); // 結果表 示 3 echo $result['body']; } catch (S3Exception $e) { echo '*** Error ***'. "\n"; echo $e- >getmessage(); } 2 1 S3 クライアント作成 2 getobject 実 行行 Bucket を指定 Key は ファイル名 3 取得したコンテンツを表 示 (*) 事前に Bucket が作成されている必要があります
サンプル :SQS - sendmessage API 仕様 : http://docs.aws.amazon.com/aws- sdk- php/latest/class- Aws.Sqs.SqsClient.html#_ sendmessage <?php require '/path/to/vendor/autoload.php'; use Aws\Common\Aws; use Aws\Sqs\Exception\SqsException; try { $client = SqsClient::factory; 1 $queueurl = 'https://yourqueue'; $result = $client- >sendmessage(array( 2 'QueueUrl' => $queueurl, 'MessageBody' => 'Send Message!', )); // 結果表 示 var_ dump($result); } catch (SqsException $e) { echo '*** Error ***'. "\n"; echo $e- >getmessage(); } 1 SQS クライアント作成 2 sendmessage 実 行行 QueueURL を指定 送りたいメッセージを指定 (*) 事前に Queue が作成されている必要があります
サンプル :SQS - receivemessage API 仕様 : http://docs.aws.amazon.com/aws- sdk- php/latest/class- Aws.Sqs.SqsClient.html#_ receivemessage <?php require '/path/to/vendor/autoload.php'; use Aws\Common\Aws; use Aws\Sqs\Exception\SqsException; try { $client = SqsClient::factory; 1 $queueurl = 'https://yourqueue'; $result = $client- >receivemessage(array( 'QueueUrl' => $queueurl, )); // 結果表 示 var_ dump($result); } catch (SqsException $e) { echo '*** Error ***'. "\n"; echo $e- >getmessage(); } 2 1 コンフィグを指定してインスタンス作成 2 SQS クライアント作成 3 receivemessage 実 行行 QueueURL を指定 (*) 事前に Queue が作成されている必要があります
サンプル :DynamoDB - putitem API 仕様 : http://docs.aws.amazon.com/aws- sdk- php/latest/class- Aws.DynamoDb.DynamoDbClient.html#_ putitem <?php require '/path/to/vendor/autoload.php'; use Aws\Common\Aws; use Aws\DynamoDb\Exception\DynamoDbException; try { $client = DynamoDbClient::factory; 1 $result = $client- >putitem(array( 'TableName' => ʼ table_ name', 'Item' => $client- >formatattributes(array( 2 ʼ id' => 100, 'timestamp' => 130699342, 'message' => 'Good Morning.', )), )); // 結果表 示 var_ dump($result); } catch (DynamoDbException $e) { echo '*** Error ***'. "\n"; echo $e- >getmessage(); } 1 DynamoDB クライアント作成 2 putitem 実 行行 - TableName: テーブル名 - Item: Putするアイテムを指定 ( 例例 ) id : Hash Key timestamp : Range Key message : Attribute (*) 事前に Table が作成されている必要があります
サンプル :DynamoDB - getitem API 仕様 : http://docs.aws.amazon.com/aws- sdk- php/latest/class- Aws.DynamoDb.DynamoDbClient.html#_ getitem <?php require '/path/to/vendor/autoload.php'; use Aws\Common\Aws; use Aws\DynamoDb\Exception\DynamoDbException; try { $client = DynamoDbClient::factory; $result = $client- >getitem(array( 'ConsistentRead' => true, 'TableName' => 'table_ name', 'Key' => array( ʼ id' => array('n' => '100'), 'timestamp' => array('n' => '130699342') ) )); // 結果表 示 var_ dump($result); } catch (DynamoDbException $e) { echo '*** Error ***'. "\n"; echo $e- >getmessage(); } 1 2 1 DynamoDB クライアント作成 2 getitem 実 行行 - TableName: テーブル名 - Key:GetするアイテムのKey を指定 ( 例例 ) id : Hash Key timestamp : Range Key (*) 事前に Table が作成されている必要があります
活 用法! PHP アプリのバックエンドストレージ呼び出し DynamoDB,SQS,S3 を簡単に呼び出し可能! PHP ベースのアプリケーションの拡張 Wordpress や EC- Cube などの PHP ベースのアプリケーションと AWS の連携! 独 自の管理理 用 Web インターフェースの作成 定型作業を簡略略化したり 管理理を容易易にするための独 自 Web インターフェースの作成
PHP 版 SDK の便便利利なクラス! DynamoDBSessionHandler! DynamoDB を使った HTTP のセッション共有が可能 EC2 DynamoDB ELB EC2 EC2 速い消えない管理不要
DynamoDBSessionHandler の利利 用 <?php require '/home/ec2- user/vendor/autoload.php'; use Aws\Common\Aws; use Aws\DynamoDb\Exception\DynamoDbException; use Aws\DynamoDb\DynamoDbClient; use Aws\DynamoDb\Session\SessionHandler; $aws = Aws::factory(ʼ aws- config.php'); $client = $aws- >get('dynamodb'); try { $sessionhandler = SessionHandler::factory(array( 'dynamodb_ client' => $client, 'table_ name' => 'sessions', )); $sessionhandler- >register(); } catch (DynamoDbException $e) { echo '*** Error ***'. "\n"; echo $e- >getmessage(); } session_ start(); // セッションにデータ登録 $_ SESSION['username'] = 'jeremy'; $_ SESSION['role'] = 'admin'; session_ commit();
boto(python)
boto とは! Python 用の AWS SDK のデファクトスタンダード! 最新版は 2.19.0 (2013 年年 12 月現在 )! Python 2.6.6, 2.7.3 on Mac OSX and Ubuntu Maverick で動作確認している! Python 2.5 での互換性もなるべく考慮しているが保証外! Python 3.x 版は Developer Preview 中
操作可能サービス Direct Connect Elasticache IAM EC2 SimpleDB OpsWorks ELB S3 Elastic Transcoder Auto Scaling Glacier SQS EMR CloudFront SNS Route53 Storage Gateway SES VPC Import/Export SWF DynamoDB Elastic Beanstalk CloudSearch RDS Cloud Formation Data Pipeline Redshift Cloud Watch CloudTrail FPS EBS
boto に関するリソース! ソースコードリポジトリ https://github.com/boto/boto! PyPI http://pypi.python.org/pypi/boto! オンラインドキュメント http://docs.pythonboto.org/! IRC http://webchat.freenode.net/?channels=boto 2012 2013 Amazon.com, Inc. and its affiliates. All All rights rights reserved. reserved. May May not be not copied, be copied, modified modified or distributed or distributed in whole or in in whole part without or in part the express without consent the express of Amazon.com, consent of Inc. Amazon.com, Inc.
インストール $ pip install boto 2012 2013 Amazon.com, Inc. and its affiliates. All All rights rights reserved. reserved. May May not be not copied, be copied, modified modified or distributed or distributed in whole or in in whole part without or in part the express without consent the express of Amazon.com, consent of Inc. Amazon.com, Inc.
初期設定! 設定ファイルの作成! /etc/boto.cfg - グローバルな設定を記述! ~ /.boto ユーザー毎の設定を記述 [Boto] debug = 0 num_ retries = 10 [DynamoDB] region = ap- northeast- 1 2012 2013 Amazon.com, Inc. and its affiliates. All All rights rights reserved. reserved. May May not be not copied, be copied, modified modified or distributed or distributed in whole or in in whole part without or in part the express without consent the express of Amazon.com, consent of Inc. Amazon.com, Inc.
サンプル :S3 set_ contents_ from_ string >>> from boto.s3.connection import S3Connection >>> conn = S3Connection() >>> bucket_ name = yourbucket" >>> bucket = conn.get_ bucket(bucket_ name) >>> from boto.s3.key import Key >>> k = Key(bucket) >>> k.key = "test.txt" >>> k.set_ contents_ from_ string("hello World!") (*) 事前に Bucket が作成されている必要があります
サンプル :S3 get_ contents_ as_ string >>> from boto.s3.connection import S3Connection >>> conn = S3Connection() >>> bucket_ name = "yourbucket" >>> bucket = conn.get_ bucket(bucket_ name) >>> from boto.s3.key import Key >>> k = Key(bucket) >>> k.key = "test.txt" >>> k.get_ contents_ as_ string() (*) 事前に Bucket が作成されている必要があります
サンプル :SQS write >>> import boto.sqs >>> conn = boto.sqs.connect_ to_ region("ap- northeast- 1") >>> q = conn.get_ queue('yourqueue') >>> from boto.sqs.message import Message >>> m = Message() >>> m.set_ body('hello World!!') >>> q.write(m) (*) 事前に Queue が作成されている必要があります
サンプル :SQS get_ messages >>> import boto.sqs >>> conn = boto.sqs.connect_ to_ region("ap- northeast- 1") >>> q = conn.get_ queue('yourqueue') >>> rs = q.get_ messages() >>> m = rs[0] >>> m.get_ body() 'Hello World!!' (*) 事前に Queue が作成されている必要があります
サンプル :DynamoDB putitem >>> from boto.dynamodb2.items import Item >>> from boto.dynamodb2.table import Table >>> table = Table('table_ name') >>> item = Item(table, data={... ʼ id': 100,... 'timestamp': 130699342,... 'message' : 'Good Morning.',... }) >>> item.save() True (*) 事前に Table が作成されている必要があります
サンプル :DynamoDB getitem >>> from boto.dynamodb2.table import Table >>> table= Table('table_ name') >>> item = table.get_ item(id=100,timestamp=130699342) >>> print item['message'] Good Morning. (*) 事前に Table が作成されている必要があります
その他 Tips! AWS コマンドラインインタフェース (CLI) も boto を 一部利利 用している
AWS SDK for Ruby
AWS SDK for Ruby とは! Amazon 提供の AWS 開発 用の Ruby 向け SDK! 現在のバージョン Version 1 (stable) Version 2 (developer preview)! http://aws.amazon.com/sdkforruby/! 環境 :Ruby 1.8.7 以降降
操作可能サービス Direct Connect Elasticache IAM EC2 SimpleDB OpsWorks ELB S3 Elastic Transcoder Auto Scaling Glacier SQS EMR CloudFront SNS Route53 Storage Gateway SES VPC Import/Export SWF DynamoDB Elastic Beanstalk CloudSearch RDS Cloud Formation Data Pipeline Redshift Cloud Watch
! Ruby 環境のセットアップ Rbenv を利利 用する 利利 用 方法 https://github.com/sstephenson/rbenv RVM を利利 用する https://rvm.io/! aws- sdk gem をインストール $ gem install aws- sdk
設定の初期化! デフォルトのリージョンをセッティング require 'awsʼ AWS.config({ :region => ʻ YOUR_ DEFAULT_ REGIONʼ })
サンプル :S3 - write API 仕様 : http://docs.aws.amazon.com/awsrubysdk/latest/aws/s3/s3object.html#write- instance_ method #!/usr/bin/env ruby require 'aws' 1 AWS.config({ :access_ key_ id => ENV['AWS_ ACCESS_ KEY_ ID'], :secret_ access_ key => ENV['AWS_ SECRET_ ACCESS_ KEY'], :region => ENV['AWS_ REGION'] }) 2 s3 = AWS::S3.new bucket = s3.buckets['your- bucket'] obj = bucket.objects['key'] obj.write(pathname.new('/path/to/file.txt')) 3 1 コンフィグを指定 2 S3 クライアント作成し bucket や key を指定 3 put する file 名を指定し s3 に put (*) 事前に Bucket が作成されている必要があります
サンプル :S3 - read API 仕様 : http://docs.aws.amazon.com/awsrubysdk/latest/aws/s3/s3object.html#read- instance_ method #!/usr/bin/env ruby require 'aws' AWS.config({ :access_ key_ id => ENV['AWS_ ACCESS_ KEY_ ID'], :secret_ access_ key => ENV['AWS_ SECRET_ ACCESS_ KEY'], :region => ENV['AWS_ REGION'] }) s3 = AWS::S3.new bucket = s3.buckets['your- bucket'] obj = bucket.objects['key'] obj.read do chunk puts chunk #=> data of s3://your- bucket/key end 1 2 3 1 コンフィグを指定 2 S3 クライアント作成し bucket や key を指定 3 s3 にある object のデータを取得 (*) 事前に Bucket が作成されている必要があります
サンプル :SQS send_ message API 仕様 : http://docs.aws.amazon.com/awsrubysdk/latest/aws/sqs/ Client.html#send_ message- instance_ method #!/usr/bin/env ruby require 'aws' require 'pp' AWS.config({ :access_ key_ id => ENV['AWS_ ACCESS_ KEY_ ID'], :secret_ access_ key => ENV['AWS_ SECRET_ ACCESS_ KEY'], :region => ENV['AWS_ REGION'] }) sqs = AWS::SQS.new queue_ url = 'https://your_ queue' result = sqs.client.send_ message({ :queue_ url => queue_ url, :message_ body => 'Send Message!' }) pp result 1 2 3 1 コンフィグを指定 2 SQS クライアント作成 3 send_ message 実 行行 queue_ url を指定 送りたいメッセージを指定 (*) 事前に Queue が作成されている必要があります
サンプル :SQS receive_ message API 仕様 : http://docs.aws.amazon.com/awsrubysdk/latest/aws/sqs/ Client.html#receive_ message- instance_ method #!/usr/bin/env ruby require 'aws' require 'pp' AWS.config({ :access_ key_ id => ENV['AWS_ ACCESS_ KEY_ ID'], :secret_ access_ key => ENV['AWS_ SECRET_ ACCESS_ KEY'], :region => ENV['AWS_ REGION'] }) sqs = AWS::SQS.new queue_ url = 'https://your_ queue' result = sqs.client.receive_ message({ :queue_ url => queue_ url }) pp result 1 2 3 1 コンフィグを指定 2 SQS クライアント作成 3 receive_ message 実 行行 queue_ url を指定 (*) 事前に Queue が作成されている必要があります
サンプル :DynamoDB put_ item API 仕様 : http://docs.aws.amazon.com/awsrubysdk/latest/aws/dynamodb/client.html#put_ item- instance_ method #!/usr/bin/env ruby require 'aws' require 'pp' AWS.config({ :access_ key_ id => ENV['AWS_ ACCESS_ KEY_ ID'], :secret_ access_ key => ENV['AWS_ SECRET_ ACCESS_ KEY'], :region => ENV['AWS_ REGION'] }) client = AWS::DynamoDB::Client.new result = client.put_ item({ :table_ name => 'table_ nameʼ, :item => { 'id' => {:n => '100'}, 'timestamp' => {:n => '130699342'}, 'message' => {:s => 'Good Morning'} } }) pp result #=> {"ConsumedCapacityUnits"=>1.0} 1 2 3 1 コンフィグを指定 2 DynamoDB クライアント作成 3 put_ item 実 行行 - :table_ name: テーブル名 - :item: Putするアイテムを指定 ( 例例 ) id : Hash Key timestamp : Range Key message : Attribute (*) 事前に Table が作成されている必要があります
サンプル :DynamoDB get_ item API 仕様 : http://docs.aws.amazon.com/awsrubysdk/latest/aws/dynamodb/client.html#get_ item- instance_ method #!/usr/bin/env ruby require 'aws' require 'pp' AWS.config({ :access_ key_ id => ENV['AWS_ ACCESS_ KEY_ ID'], :secret_ access_ key => ENV['AWS_ SECRET_ ACCESS_ KEY'], :region => ENV['AWS_ REGION'] }) client = AWS::DynamoDB::Client.new result = client.get_ item({ :consistent_ read => true, :table_ name => 'table_ name', :key => { :hash_ key_ element => {:n => '100'}, :range_ key_ element => {:n => '130699342'} } }) pp result #=> {"Item"=>{"id"=>{"N"=>"100"}, "message"=>{"s"=>"good Morning"}, "timestamp"=>{"n"=>"130699342"}}, "ConsumedCapacityUnits"=>1.0} 1 2 3 1 コンフィグを指定 2 DynamoDB クライアント作成 3 get_ item 実 行行 - :table_ name テーブル名 - :consistent_ read 一貫性 - :key GutするKeyを指定 ( 例例 ) id : Hash Key timestamp : Range Key (*) 事前に Table が作成されている必要があります
その他 Tips! 新しい Ruby SDK (version 2) Developer Preview バリデーション ドキュメント 拡張性など改善 プラグイン 方式をとっている Ruby 1.9 以降降が必須! 以下のように利利 用可能 $ gem install aws- sdk- core AWS::DynamoDB.new(api_ version: ʻ 2012-08- 10ʼ ) Re:Invent で発表された新 Ruby SDK のスライドはおすすめ
その他 Tips! Rails のセッションを DynamoDB に保存 スケーラブルかつ耐障害に優れたセッションストア Rails 3.x か 4.x から利利 用可能 Rack ベースのアプリも利利 用可能! 以下の 手順で利利 用可能 gem ʻ aws- sessionstore- dynamodbʼ $ bundle install 参考 :https://github.com/aws/aws- sessionstore- dynamodb- ruby
AWS SDK for JavaScript in Node.js
AWS SDK for JavaScript in Node.js とは! Amazon 提供の AWS 開発 用の node.js 環境で動く JavaScript 向け SDK http://aws.amazon.com/sdkfornodejs/
操作可能サービス Direct Connect Elasticache IAM EC2 SimpleDB OpsWorks ELB S3 Elastic Transcoder Auto Scaling Glacier SQS EMR CloudFront SNS Route53 Storage Gateway SES VPC Import/Export SWF DynamoDB Elastic Beanstalk CloudSearch RDS Cloud Formation Data Pipeline Redshift Cloud Watch
利利 用 方法! Node.js 環境のセットアップ OS のパッケージマネージャーで npm をインストール Mac の場合 : $ brew install npm! aws- sdk package をインストール $ npm install aws- sdk
サンプル :S3 - putobject var AWS = require('aws- sdk'); var fs = require('fs'); var s3 = new AWS.S3(); 1 var bodystream = fs.createreadstream( '/path/ 2 to/file.txt' ); var params = { Bucket: 'your- bucket', Key: 'key', Body: bodystream }; s3.putobject(params, function(err, data) { 3 if (err) console.log(err); else console.log("successfully uploaded."); }); 1 S3 クライアント作成 2 put 時の引数 Bucket: s3 bucket Key: s3 key Body: 実際のデータ 3 S3 へ PUT (*) 事前に Bucket が作成されている必要があります
サンプル :S3 - getobject var AWS = require('aws- sdk'); var fs = require('fs'); var s3 = new AWS.S3(); var params = { Bucket: ʼ your- bucket', Key: ʼ key' }; s3.getobject(params, function(err, data) { if (err) console.log(err); else console.log(data.body.tostring()); }); 1 2 3 1 S3 クライアント作成 2 gut 時の引数 Bucket: s3 bucket Key: s3 key 3 S3 からデータ取得 (*) 事前に Bucket が作成されている必要があります
サンプル :SQS - sendmessage var AWS = require('aws- sdk'); var fs = require('fs'); var s3 = new AWS.SQS(); 1 var params = { 2 QueueUrl: 'https://your_ queue', MessageBody: 'Send Message!' } sqs.sendmessage(params, function(err, data) { if (err) console.log(err); else console.log("successfully sent."); }) 1 SQS クライアント作成 2 queue_ url を指定 送りたいメッセージを指定 3 sendmessage 実 行行 (*) 事前に Queue が作成されている必要があります
サンプル :SQS - receivemessage var AWS = require('aws- sdk'); var fs = require('fs'); var s3 = new AWS.SQS(); 1 var params = { QueueUrl: 'https://your_ queueʼ 2 } sqs.receivemessage(params, function(err, data) { 3 if (err) console.log(err); else console.log(data); }) 1 SQS クライアント作成 2 queue_ url を指定 3 receivemessage 実 行行 (*) 事前に Queue が作成されている必要があります
サンプル :DynamoDB putitem var AWS = require('aws- sdk'); var fs = require('fs'); var ddb = new AWS.DynamoDB(); var params = { TableName: 'my_ table', Item: { 'id': {N: ʻ 100'}, 'timestamp': {N: '130699342'}, 'message': {S: 'Good Morning'} } }; ddb.putitem(params, function(err, data) { if (err) console.log(err); else console.log(data); }); 1 2 3 1 DynamoDB クライアント作成 2 パラメータ指定 - :TableName: テーブル名 - :Item: Putするアイテムを指定 ( 例例 ) id : Hash Key timestamp : Range Key message : Attribute 3 Put 実 行行 (*) 事前に Table が作成されている必要があります
サンプル :DynamoDB getitem var AWS = require('aws- sdk'); var fs = require('fs'); var ddb = new AWS.DynamoDB(); var params = { TableName: 'my_ table', Key: { 'id': {N: ʻ 100'}, 'timestamp': {N: '130699342'} } }; ddb.getitem(params, function(err, data) { if (err) console.log(err); else console.log(data); }); 1 2 3 1 DynamoDB クライアント作成 2 パラメータ指定 - :TableName: テーブル名 - :Item: Putするアイテムを指定 ( 例例 ) id : Hash Key timestamp : Range Key message : Attribute 3 Get 実 行行 (*) 事前に Table が作成されている必要があります
まとめ
今回のまとめ! AWS はプログラマブルなインフラ ほぼすべてのサービスはマネジメントコンソールから利利 用できるが 自動化しようと思ったらプログラムから扱うのが必須 自動化すると AWS は何倍も便便利利になる! AWS のサービスは HTTP/HTTPS で REST/SOAP 形式の API をサポート 例例えば EC2 : Start/Stop/Terminate S3 : GetObject/PutObject DynamoDB : Get/Put! SDK はこれらの API を抽象化し 各 言語からの利利 用を 非常に簡単にしてくれる
Q&A 68 2012 Amazon.com, Inc. and its affiliates. All rights reserved. May not be copied, modified or distributed in whole or in part without the express consent of Amazon.com, Inc.