aws

AWS CloudFormation

How AWS CloudFormation templates work: the sections of a template, plus JSON and YAML examples that launch an EC2 instance with SSH access and a Windows server.

AWS CloudFormation lets you launch AWS resources from json or yaml template files instead of clicking through the console. It’s known as IaaS (Infrastructure As A Service).

Structure of a template

  • AWS Template Format Version: The version of the template file.
  • Description: A description of what the template does, written by its author. It’s a string field.
  • MetaData: Properties of the template.
  • Parameters: Values you pass in to the template.
  • Mappings: Dependencies between your AWS resources.
  • Conditions: Added when the stack is created.
  • Outputs: Displayed once the stack finishes creating.
  • Resources: The AWS resources you want to create. This is the most important part.

Example: an EC2 instance with SSH access

Here’s a CloudFormation template that launches an EC2 instance with SSH access:

json
{
  "Description": "Create an EC2 instance by AWS CloudFormation",
  "Resources": {
    "SecurityGroupDemoSvrTraffic": {
      "Type": "AWS::EC2::SecurityGroup",
      "Properties": {
        "GroupName": "ssh-group",
        "SecurityGroupIngress": [
          {
            "IpProtocol": "tcp",
            "FromPort": 22,
            "ToPort": 22,
            "CidrIp": "0.0.0.0/0",
            "Description": "For traffic from Internet"
          }
        ],
        "GroupDescription": "Security Group for demo server",
        "VpcId": "[Find you VpcId in VPC-->Subnets]"
      }
    },
    "EC2InstanceDemoSvr": {
      "Type": "AWS::EC2::Instance",
      "Properties": {
        "AvailabilityZone": "[Find you AvailabilityZone in VPC-->Subnets]",
        "ImageId": "[Find your ImageId in EC2-->Launch Instance-->Step1]",
        "InstanceType": "[Find your InstanceType in EC2-->Launch Instance-->Step2]",
        "KeyName": "[Find your KeyName in EC2-->Key Pairs]"
      }
    }
  }
}

Launching a Windows instance

This template starts a Windows EC2 instance:

yaml
Description: "A simple script that starts Window EC2 instances on AWS Cloud"
Resources:
  WinInstance:
    Type: "AWS::EC2::Instance"
    Properties:
      SecurityGroups:
        - !Ref InstanceGroupSecurity
      InstanceType: # t1.micro
      KeyName: # Your key
      ImageId: ""
  InstanceGroupSecurity:
    Type: "AWS::EC2::SecurityGroup"
    Properties:
      GroupDescription: '' # Description
      SecurityGroupIngress:
        - IpProtocol: # Enter Protocol Like TCP
          FromPort: # RDP Port
          ToPort: 3389
          CidrIp: 0.0.0.0/0