Cloud Formation Template for EC2
Simple example of setting up an EC2 instance along with a Security Group which allows SSH to the launched instance.
Template
https://raw.githubusercontent.com/rishiraaz/AWS/master/CloudFormation/Simple-EC2.yaml
The cloud formation template being used is written in YAML. Brief explanation of what each term means:
AWSTemplateFormatVersion: Specifies the AWS CloudFormation template version.
Description: A text string that describes the template.
Mappings: A mapping of keys and associated values that you can use to specify conditional parameter values(CloudFormation’s version of a “case” statement).
Outputs: Describes the values that are returned whenever you view your stack’s properties. This gets displayed in the AWS CloudFormation Console.
Parameters: Specifies values that you can pass in to your template at runtime.
Resources: Specifies the stack resources and their properties, like our EC2 instance. Mandatory property for this example.
T
The most important top-level properties of a CloudFormation template are Parameters and Resources. The resources section is where our EC2 instance is defined. This EC2Instance resource demonstrates uses of Ref. Ref is a way to reference values from other parts of the template.
Ref: InstanceType also refers to the InstanceType parameter that can be passed in.
The default parameter for the EC2 Instance type to launch is t2.small, can be overriden during laucnh of instance. For parameters with default values, no need to provide the parameter. For parameters without default values, need to provide the parameter. In this specific template, the only required parameter is the KeyName.
Command to launch the stack
$ aws cloudformation create-stack — template-body file://templates/single_instance.yml — stack-name single-instance — parameters ParameterKey=KeyName,ParameterValue=tutorial ParameterKey=InstanceType,ParameterValue=t2.micro
Output
Upon successfully launching the CloudFormation stack, output will be similar to this:
{
“StackId”: “arn:aws:cloudformation:us-west-2:1606191131234:stack/single-instance/3401e900–3d83–11e7-bb7e-503f2a2cee4a”
}
Cleanup
Let’s destroy the resources.
aws cloudformation delete-stack — stack-name single-instance