![](/img/trans.png)
[英]Associate existing IAM role with EC2 instance in CloudFormation
[英]AWS Cloudformation template with EC2 instance that has IAM role to terminate that Cloudformation stack
我想創建一個可終止的Cloudformation堆棧來運行批處理作業,此作業隨后將終止。 因此,我想使用具有IAM角色的EC2實例的Cloudformation模板來終止該Cloudformation堆棧。
這是最小的CloudFormation堆棧,可通過運行aws cloudformation delete-stack
從EC2實例aws cloudformation delete-stack
:
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
語句列表中。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.