如何为ECS任务分配IAM角色



ECS任务可以分配IAM角色,以使与AWS API进行通信无需将用户凭据传递到任务。这适用于AWS CLI和SDK。这里有很好的文档,但我找不到一个涵盖所有细节的适当示例,我将创建一个自我答复的问题来节省他人的痛苦。

我创建了一个带有完整示例的git回购。重要位是:

  • 使用AushoLolelePolicyDocument创建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 SDK将自动检测到容器是否可以访问角色凭据并本身初始化。除了创建API对象外,您不必进行任何初始化。

 var AWS = require('aws-sdk');
 var cw = new AWS.CloudWatch();
 var s3 = new AWS.S3();

相关内容

  • 没有找到相关文章

最新更新