我想创建一个可终止的Cloudformation堆栈来运行批处理作业,然后终止它自己。 所以我想要一个具有IAM角色的EC2实例的Cloudformation模板来终止该Cloudformation堆栈。
答案 0 :(得分:0)
这是一个最小的CloudFormation堆栈,它通过运行aws cloudformation delete-stack
从EC2实例中自毁:
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}
请注意,如果您添加任何其他资源,则需要添加相应的'删除' IAM对EC2Policy
语句列表的权限。