CloudFormation template for EC2 and Security Group creation

Below template can be used to create EC2 instance and associate Security Group with the EC2 instance which enables SSH.

AWSTemplateFormatVersion : 2010-09-09
Description: Template to create an EC2 instance and enable SSH access to the instance
Parameters:
KeyName:
Description: Name of an existing EC2 KeyPair to enable SSH access to the instance
Type: 'AWS::EC2::KeyPair::KeyName'
ConstraintDescription: Provide the name of an existing SSH key pair Resources:
MyEC2Instance:
Type: 'AWS::EC2::Instance'
Properties:
InstanceType: t2.micro
ImageId: ami-0f2176987ee50226e
SecurityGroups:
- !Ref InstanceSecurityGroup
KeyName: !Ref KeyName
Tags:
- Key: Name
Value: My First CF Instance
InstanceSecurityGroup:
Type: 'AWS::EC2::SecurityGroup'
Properties:
GroupDescription: Enable SSH access via port 22
SecurityGroupIngress:
IpProtocol: tcp
FromPort: 22
ToPort: 22
CidrIp: 0.0.0.0/0
Outputs:
InstanceID:
Description: The Instance ID
Value: !Ref MyEC2Instance

Save above file with .yml extension.

The only thing we need to change in the above template is ImageId: ami-0f2176987ee50226e .

Image IDs are based on the region. Login to your AWS account Go to your EC2 and Click Launch Instance. Copy Image ID as shown in image below and past it in the template.

Template is ready to create the stack.

In AWS console, Go to Services -> Manage & Governance -> CloudFormation

Click “Create New Stack” button.

Choose file from your location and Click Next

Enter Stack name and Select key pair from the drop down and click Next.

In the option page, Click Next

In the Review page, Click Create

Stack creation started.

Once the process completed. Go to EC2 page. You will see instance created with Security Group.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s