需要在 CloudFormation 模板中为 ECS 集群资源配置一个服务角色。示例代码如下:
Resources:
ECSCluster:
Type: AWS::ECS::Cluster
Properties:
ClusterName: my-cluster
# 配置服务角色
RoleArn: !GetAtt ECSClusterRole.Arn
ECSClusterRole:
Type: AWS::IAM::Role
Properties:
# 添加策略以授予权限
AssumeRolePolicyDocument:
Version: 2012-10-17
Statement:
- Effect: Allow
Principal:
Service: ecs.amazonaws.com
Action: sts:AssumeRole
Policies:
- PolicyName: ECSPermissions
PolicyDocument:
Version: 2012-10-17
Statement:
- Effect: Allow
Action:
- logs:CreateLogGroup
- logs:CreateLogStream
- logs:PutLogEvents
Resource: arn:aws:logs:*:*:*
在上面的示例中,我们为 ECS 集群资源 ECSCluster
配置了服务角色 ECSClusterRole
,并授权了 ECS 集群可以执行 CloudWatch Logs 的相关操作。这样,在使用 CloudFormation 创建 ECS 集群时,就能够自动扮演服务角色并成功创建集群了。