Reputation: 388
I'm trying to get my CloudFormation stack to delete itself when it is complete. When I try the following code in my template, the logs show me that the file or command was not found.
When I use runuser to execute other AWS CLI commands I have no problem (as long as the command doesn't require options that start with "--").
I am using the basic AWS IAM.
"06_delete_stack": { "command": { "Fn::Join": [ "", [
"runuser -u fhwa 'aws cloudformation delete-stack --stack-name ", { "Ref": "StackName" }, "'"
] ] },
"cwd": "/var/log"}
Upvotes: 1
Views: 1465
Reputation: 20390
Expanding upon Joel's answer, here's a minimal CloudFormation stack that self-destructs from an EC2 instance by running aws cloudformation delete-stack
, with an AWS::IAM::Role
granting least privilege to delete itself:
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}
Note that if you add any additional resources to the template, you'll need to add the corresponding 'delete' IAM permission to the EC2Policy
statement list.
Upvotes: 8
Reputation: 388
I was able to get the stack to delete itself.
I had the stack build an additional shell script that contained the AWS CLI command to delete the stack. I then adjusted the runuser command to execute the shell script.
I then had to add the IAM permissions to delete the stack to the role for the generated user.
Upvotes: 1