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
Description: Name of an existing EC2 KeyPair to enable SSH access to the instance
ConstraintDescription: Provide the name of an existing SSH key pair Resources:
- !Ref InstanceSecurityGroup
KeyName: !Ref KeyName
- Key: Name
Value: My First CF Instance
GroupDescription: Enable SSH access via port 22
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.