4
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

ECSでaws-sdkを使うときはTaskRoleを正しく設定すればアクセスキーは不要

Last updated at Posted at 2021-09-12

概要

表題の通り。
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:

  1. Loaded from AWS Identity and Access Management (IAM) roles for Amazon EC2
  2. Loaded from the shared credentials file (~/.aws/credentials)
  3. Loaded from environment variables
  4. Loaded from a JSON file on disk
  5. 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

参考

4
5
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?