我试图让我的CloudFormation堆栈在完成后自行删除。当我在模板中尝试以下代码时,日志显示我找不到文件或命令。
当我使用runuser执行其他AWS CLI命令时,我没有问题(只要该命令不需要以&#34开头的选项; - ")。
我正在使用基本的AWS IAM。
"06_delete_stack": { "command": { "Fn::Join": [ "", [
"runuser -u fhwa 'aws cloudformation delete-stack --stack-name ", { "Ref": "StackName" }, "'"
] ] },
"cwd": "/var/log"}
答案 0 :(得分:6)
展开Joel's answer,这是一个最小的CloudFormation堆栈,它通过运行aws cloudformation delete-stack
从EC2实例中自毁,并AWS::IAM::Role
授予最低权限以自行删除:< / p>
Description: Cloudformation stack that self-destructs
Mappings:
# amzn-ami-hvm-2016.09.1.20161221-x86_64-gp2
RegionMap:
us-east-1:
"64": "ami-9be6f38c"
Resources:
EC2Role:
Type: AWS::IAM::Role
Properties:
RoleName: !Sub "EC2Role-${AWS::StackName}"
AssumeRolePolicyDocument:
Version: 2012-10-17
Statement:
- Effect: Allow
Principal:
Service: [ ec2.amazonaws.com ]
Action: [ "sts:AssumeRole" ]
Path: /
Policies:
- PolicyName: EC2Policy
PolicyDocument:
Version: 2012-10-17
Statement:
- Effect: Allow
Action:
- "cloudformation:DeleteStack"
Resource: !Ref "AWS::StackId"
- Effect: Allow
Action: [ "ec2:TerminateInstances" ]
Resource: "*"
Condition:
StringEquals:
"ec2:ResourceTag/aws:cloudformation:stack-id": !Ref AWS::StackId
- Effect: Allow
Action: [ "ec2:DescribeInstances" ]
Resource: "*"
- Effect: Allow
Action:
- "iam:RemoveRoleFromInstanceProfile"
- "iam:DeleteInstanceProfile"
Resource: !Sub "arn:aws:iam::${AWS::AccountId}:instance-profile/*"
- Effect: Allow
Action:
- "iam:DeleteRole"
- "iam:DeleteRolePolicy"
Resource: !Sub "arn:aws:iam::${AWS::AccountId}:role/EC2Role-${AWS::StackName}"
RootInstanceProfile:
Type: AWS::IAM::InstanceProfile
Properties:
Path: /
Roles: [ !Ref EC2Role ]
WebServer:
Type: AWS::EC2::Instance
Properties:
ImageId: !FindInMap [ RegionMap, !Ref "AWS::Region", 64 ]
InstanceType: m3.medium
IamInstanceProfile: !Ref RootInstanceProfile
UserData:
"Fn::Base64":
!Sub |
#!/bin/bash
aws cloudformation delete-stack --stack-name ${AWS::StackId} --region ${AWS::Region}
请注意,如果您向模板添加任何其他资源,则需要添加相应的&#39;删除&#39; IAM对EC2Policy
语句列表的权限。
答案 1 :(得分:0)
我能够让堆栈自行删除。
我让堆栈构建了一个额外的shell脚本,其中包含用于删除堆栈的AWS CLI命令。然后我调整了runuser命令来执行shell脚本。
然后我必须添加IAM权限以将堆栈删除为生成用户的角色。