问题描述
APITaskDeFinition:
Type: 'AWS::ECS::TaskDeFinition'
Properties:
...
ExecutionRoleArn:
<RoleADeFinition here>
...
TaskRoleArn:
<RoleBDeFinition here>
...
鉴于这些角色只会被此资源 APITaskDeFinition
使用,这将是很好的做法,并且被认为是为每个需要一个角色的资源使用特定角色的最佳做法
解决方法
我不相信我们可以通过 CloudFormation 做到这一点。
标准做法是将所有资源一起定义在一个模板中并引用。
EcsTaskExecutionRole:
Type: 'AWS::IAM::Role'
Properties:
AssumeRolePolicyDocument:
Statement:
- Effect: Allow
Principal:
Service:
- ecs-tasks.amazonaws.com
Action:
- 'sts:AssumeRole'
Path: /
Policies:
- PolicyName: ecs-taskExecution
PolicyDocument:
Statement:
- Effect: Allow
Action:
- 'ecr:GetAuthorizationToken'
- 'ecr:BatchCheckLayerAvailability'
- 'ecr:GetDownloadUrlForLayer'
- 'ecr:BatchGetImage'
- 'logs:CreateLogStream'
- 'logs:PutLogEvents'
Resource: '*'
和 !GetAtt EcsTaskExecutionRole.Arn
ContainerTaskdefinition:
Type: 'AWS::ECS::TaskDefinition'
Properties:
Family: !Ref 'AWS::StackName'
ExecutionRoleArn: !GetAtt EcsTaskExecutionRole.Arn <-- refer to task Arn
TaskRoleArn: !GetAtt EcsTaskExecutionRole.Arn <-- refer to task Arn
Cpu: '256'
Memory: 1GB
NetworkMode: awsvpc
RequiresCompatibilities:
- EC2
- FARGATE
ContainerDefinitions:
- Name: !Ref 'AWS::StackName'
Cpu: 10
Essential: 'true'
Image: !Ref Image
Memory: '1024'
但是,使用 AWS CDK,我们可以使用更高级别的构造,该构造在大多数情况下创建具有默认权限的角色,并且可以轻松添加所需的其他权限,编译时会创建上述 cloudformation。 Here 是 ECS 构造