Skip to content

Instantly share code, notes, and snippets.

@rupertbg
Created August 19, 2019 04:37
Show Gist options
  • Save rupertbg/379c2dd6f36653387ad4bd97a85764ca to your computer and use it in GitHub Desktop.
Save rupertbg/379c2dd6f36653387ad4bd97a85764ca to your computer and use it in GitHub Desktop.
A self-deleting EC2 Instance in a Cloudformation stack
AWSTemplateFormatVersion: 2010-09-09
Description: A self-deleting EC2 instance
Parameters:
VpcId:
Type: AWS::EC2::VPC::Id
Description: VPC to use
InstanceType:
Description: EC2 instance type
Type: String
Default: t3.nano
AMIID:
Type: String
Description: Your AMI ID
Resources:
EC2InstanceRole:
Type: AWS::IAM::Role
Properties:
RoleName: !Ref AWS::StackName
AssumeRolePolicyDocument:
Statement:
- Effect: Allow
Principal:
Service:
- ec2.amazonaws.com
Action:
- sts:AssumeRole
Path: /
Policies:
- PolicyName: !Ref AWS::StackName
PolicyDocument:
Statement:
- Effect: Allow
Action:
- cloudformation:DeleteStack
Resource:
- !Sub arn:aws:cloudformation:${AWS::Region}:${AWS::AccountId}:stack/${AWS::StackName}
EC2InstanceProfile:
Type: AWS::IAM::InstanceProfile
Properties:
Path: /
Roles:
- !Ref EC2InstanceRole
EC2Instance:
Type: AWS::EC2::Instance
Metadata:
AWS::CloudFormation::Init:
config:
files:
/opt/aws/bin/somefile.txt:
content: |
here goes the contents of your file
mode: '000755'
owner: root
group: root
Properties:
ImageId: !Ref AMIID
AvailabilityZone: !Sub ${AWS::Region}a
InstanceType: !Ref InstanceType
IamInstanceProfile: !Ref EC2InstanceProfile
InstanceInitiatedShutdownBehavior: terminate
SecurityGroupIds:
- !Ref SecurityGroup
Tags:
- Key: Name
Value: SelfDeletingInstance
UserData:
Fn::Base64:
!Sub |
#!/bin/bash
set -euxo pipefail;
trap '/opt/aws/bin/cfn-signal -e 1 --resource EC2Instance --region ${AWS::Region} --stack ${AWS::StackName}' ERR;
## Your scripts go here or use AWS::CloudFormation::Init
# cfn-init
/opt/aws/bin/cfn-init -v --stack ${AWS::StackName} --resource EC2Instance --region ${AWS::Region};
/opt/aws/bin/cfn-signal -e $? --stack ${AWS::StackName} --resource EC2Instance --region ${AWS::Region};
# Terminate
sleep 30;
/opt/aws/bin/aws cloudformation delete-stack --region ${AWS::Region} --stack-name ${AWS::StackName};
/sbin/shutdown -h now;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment