概要
表題の通り。
ECSに限らないが、本番環境でaws-sdkを使うときはIAMユーザーのアクセスキーの設定は不要。
sdkはECSのタスクにattachされたRoleを自動で読み込むため、IAMユーザのアクセスキーを環境変数で渡す必要はない。
↓ sdkはとくに指定なけれattachされたroleを参照する。(EC2以外のリソースも同様)
Here are the ways you can supply your credentials in order of recommendation:
- Loaded from AWS Identity and Access Management (IAM) roles for Amazon EC2
- Loaded from the shared credentials file (~/.aws/credentials)
- Loaded from environment variables
- Loaded from a JSON file on disk
- Other credential-provider classes provided by the JavaScript SDK
ECS(fargate)でSESからメール送信する例
ECSに関するRoleはいくつかあり、その中でもコンテナの権限はTaskRoleで制御する。
↓詳しくは下記参照
ECSにattachするTaskRoleに下記policyを追加する。
ses-policy.json
{
"Sid": "sendEmailFromSES",
"Effect": "Allow",
"Action": "ses:SendEmail",
"Resource": "<arn of SES domain>"
}
ses.js
var AWS = require('aws-sdk');
AWS.config.update({region: 'us-east-1'}); //ここにSESを使うためのクレデンシャル情報の記載は不要
var ses = new AWS.SES();
var params = {
Destination: {
ToAddresses: [ 'ichiro@example.com' ]
},
Message: {
Body: {
Text: {
Data: 'こんにちは SES',
Charset: 'utf-8'
}
},
Subject: {
Data: 'こんにちは',
Charset: 'utf-8'
}
},
Source: 'jiro@example.com' // From
};
ses.sendEmail(params, function(err, data) {
if (err) console.log(err, err.stack); // an error occurred
else console.log(data); // successful response
});
ecs-taskdefinition.yml
TaskDefinition:
Type: AWS::ECS::TaskDefinition
Properties:
Family: !Ref ServiceName
Cpu: !Ref ContainerCpu
Memory: !Ref ContainerMemory
NetworkMode: awsvpc
RequiresCompatibilities:
- FARGATE
ExecutionRoleArn: !Ref ExecutionRoleArn
TaskRoleArn: !Ref TaskRoleArn #ここにSES権限を正しく設定する
ContainerDefinitions:
- Name: !Ref ServiceName
Cpu: !Ref ContainerCpu
Memory: !Ref ContainerMemory
Essential: true
Image: !Ref ImageUrl
PortMappings:
- ContainerPort: !Ref ContainerPort
LogConfiguration:
LogDriver: awslogs
Options:
awslogs-group: !Sub ${EnvironmentName}-service-${ServiceName}
awslogs-region: !Ref AWS::Region
awslogs-stream-prefix: !Ref ServiceName
参考