【问题标题】:Is it possible to define a Cloudformation Resource in-place?是否可以就地定义 Cloudformation 资源?
【发布时间】:2021-06-23 15:47:43
【问题描述】:
我有一个资源定义
APITaskDefinition:
Type: 'AWS::ECS::TaskDefinition'
Properties:
...
ExecutionRoleArn:
<RoleADefinition here>
...
TaskRoleArn:
<RoleBDefinition here>
...
考虑到这些角色只会被这个资源 APITaskDefinition 使用,这将是很棒的,并且被认为是为每个需要一个特定角色的资源使用特定角色的最佳实践
【问题讨论】:
标签:
amazon-web-services
amazon-cloudformation
amazon-iam
【解决方案1】:
我不相信我们可以使用 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 构造