CloudFormation Template for Creating EC2 with Load Balancer

CloudFormation Template for Creating EC2 with Load Balancer

Clock Icon2021.07.28

この記事は公開されてから1年以上経過しています。情報が古い可能性がありますので、ご注意ください。

AWS CloudFormation

 

CloudFormation is a way of defining  your AWS Infrastructure as Code. In CloudFormation, no resources  are created manually. The resources  created through  CloudFormation can be managed  and controlled  throughout their lifecycles. All the desired resources  and their dependencies are defined as code in  CloudFormation Template (JSON or YAML file), which is then launched  as a stack. CloudFormation also  supports graphically designing  of stack using drag-and-drop interface. CloudFormation automatically  generates Design for the templates. Templates  can be referenced  from S3 or can be directly  uploaded, while creating  a stack. Deleting a stack deletes everything that was created by CloudFormation.

 

CloudFormation Template Components

 

Resources : This is the section, where you define the required AWS resources. This section  is mandatory.

Parameters : The parameters section is used for giving  dynamic  inputs  to your template. You can customise  your template using parameters.

Mappings : It is used for specifying  static variables, where the key is matched  to the  corresponding  value.

Outputs : This is the section, where you define the output values that can be referred  in another stack by importing.

Conditions : List of conditions  can be defined  in this section  to perform resource  creation.

 

Creating CloudFormation Stack for EC2 with Load Balancer

CloudFormation Template

Create CloudFormation Template with the required resources. This template contains two EC2 Instances, two security  groups and Load Balancer.

 

---
Parameters:
  SecurityGroupDescription:
    Description: Security Group Description
    Type: String
  KeyName:
    Description: Key Pair for EC2
    Type: 'AWS::EC2::KeyPair::KeyName'

Resources:
  EC2Instance1:
    Type: AWS::EC2::Instance
    Properties:
      AvailabilityZone: us-east-2a
      ImageId: ami-0233c2d874b811deb 
      InstanceType: t2.micro
      SecurityGroups:
        - !Ref EC2SecurityGroup
      KeyName: !Ref KeyName
      UserData: 
        Fn::Base64: !Sub |
          #!/bin/bash
          yum update -y
          yum install -y httpd
          systemctl start httpd
          systemctl enable httpd
          #echo "<h1>Hello from Region us-east-2a</h1>" > /var/www/html/index.html

  EC2Instance2:
    Type: AWS::EC2::Instance
    Properties:
      AvailabilityZone: us-east-2b
      ImageId: ami-0233c2d874b811deb 
      InstanceType: t2.micro
      SecurityGroups:
        - !Ref EC2SecurityGroup
      KeyName: !Ref KeyName
      UserData: 
        Fn::Base64: !Sub |
          #!/bin/bash
          yum update -y
          yum install -y httpd
          systemctl start httpd
          systemctl enable httpd
          #echo "<h1>Hello from Region us-east-2b</h1>" > /var/www/html/index.html
          
  # security group
  ELBSecurityGroup:
    Type: AWS::EC2::SecurityGroup
    Properties:
      GroupDescription: ELB Security Group
      SecurityGroupIngress:
      - IpProtocol: tcp
        FromPort: 80
        ToPort: 80
        CidrIp: 0.0.0.0/0

  EC2SecurityGroup:
    Type: AWS::EC2::SecurityGroup
    Properties:
      GroupDescription: !Ref SecurityGroupDescription
      SecurityGroupIngress:
      - IpProtocol: tcp
        FromPort: 80
        ToPort: 80
        SourceSecurityGroupId: 
          Fn::GetAtt:
          - ELBSecurityGroup
          - GroupId
      - IpProtocol: tcp
        FromPort: 22
        ToPort: 22
        CidrIp: 0.0.0.0/0

  # Load Balancer for EC2
  LoadBalancerforEC2:
    Type: AWS::ElasticLoadBalancing::LoadBalancer
    Properties:
      AvailabilityZones: [us-east-2a, us-east-2b]
      Instances:
      - !Ref EC2Instance1
      - !Ref EC2Instance2
      Listeners:
      - LoadBalancerPort: '80'
        InstancePort: '80'
        Protocol: HTTP
      HealthCheck:
        Target: HTTP:80/
        HealthyThreshold: '3'
        UnhealthyThreshold: '5'
        Interval: '30'
        Timeout: '5'
      SecurityGroups:
        - !GetAtt ELBSecurityGroup.GroupId

 

Resources 

  • EC2 Instance - Two EC2 Instances are defined in two availability  zones [us-east-2a, us-east-2b] with UserData to install Apache Web Server [httpd].  The Instances have a reference to  EC2 Security  group and KeyPair.
  • Load Balancer - The Load Balancer is defined with Listener with port 80 (HTTP) and HealthChecks. The Load Balancer references EC2 Instances and ELB security group defined in resource section.
  • SecurityGroups
    • EC2 SecurityGroup - with Inbound rules of type SSH and HTTP with source as ELB SecurityGroupId.
    • ELB SecurityGroup - with Inbound rules of type HTTP (Internet facing).

 

Creating Stack

  • Upload the template  to S3 bucket and create a stack referring  to this S3 bucket. Copy the file URL from S3 bucket and paste it in template source URL, while creating stack.

 

 

  • Specify the Stack details by entering Stack name and parameters. Select the KeyPair for EC2 Instance and enter the description in parameter section of stack details. Click next and Create  stack with other default options.

 

 

  • The below image shows the Stack Events of resources  creation  with TimeStamp, ID, Status and Status reason.

 

  • After creating the Stack,  files in EC2 Instances can be accessed  through Load Balancer DNS.

 

Template Design

This is the template design automatically generated by CloudFormation based on the template. This Design shows the resources and their dependencies.

 

Summary

We have successfully  created EC2 Instances with Load Balancer and Security Groups using CloudFormation. CloudFormation help you in creating resources  through code and these code templates  can be reused. Through CloudFormation you can easily control and manage your Infrastructure.

 

 

Share this article

facebook logohatena logotwitter logo

© Classmethod, Inc. All rights reserved.