如何为ECS任务

时间:2017-09-16 19:33:32

标签: amazon-web-services aws-sdk amazon-iam amazon-cloudwatch amazon-ecs

可以为ECS任务分配IAM角色,以便可以与AWS API进行通信,而无需将用户凭据传递给任务。 这适用于AWS CLI和SDK。有很好的文档here但我找不到涵盖所有细节的正确例子,我会创建一个自我回答的问题,以免给别人带来痛苦。

1 个答案:

答案 0 :(得分:1)

我创建了Git repo with the full example。重要的一点是:

  • 使用AssumeRolePolicyDocument创建IAM角色定义。
  • 将IAM角色分配给任务。
  • 使用AWS JS SDK。

    IAMRole:
    Type: AWS::IAM::Role
    Properties:
        RoleName: !Sub role-task-${AWS::StackName} # Doesn't matter too much but let's make it nice anyway
        Path: / # No idea about this one but / seems to work
        # This is the funky stuff.. don't try to understand just copy-paste. Source: http://docs.aws.amazon.com/AmazonECS/latest/developerguide/task_IAM_role.html
        AssumeRolePolicyDocument: |
            {
                "Statement": [{
                    "Effect": "Allow",
                    "Principal": { "Service": [ "ecs-tasks.amazonaws.com" ]},
                    "Action": [ "sts:AssumeRole" ]
                }]
            }
        Policies:
            - PolicyName: !Sub ecs-task-${AWS::StackName}
              # You can add any actions here you want your container to be allowed to execute.
              PolicyDocument:
                {
                    "Version": "2012-10-17",
                    "Statement": [{
                            "Effect": "Allow",
                            "Action": [
                                "cloudwatch:PutMetricData" # more actions if needed
                            ],
                            "Resource": "*"
                    }]
                }
    

AWS SDK的初始化。 AWS开发工具包将自动检测容器是否可以访问角色凭据并自行初始化。除了创建API对象之外,您不必进行任何初始化。

 var AWS = require('aws-sdk');

 var cw = new AWS.CloudWatch();
 var s3 = new AWS.S3();