Dheeraj Choudhary
Dheeraj Choudhary's Blog

Dheeraj Choudhary's Blog

Deploy AWS Cloudformation Templates Using AWS CLI |  Create Launch configuration along with Security group and AutoScaling group

Deploy AWS Cloudformation Templates Using AWS CLI | Create Launch configuration along with Security group and AutoScaling group

Dheeraj Choudhary
·Jun 23, 2022·

7 min read

Subscribe to my newsletter and never miss my upcoming articles

Play this article

Table of contents

Welcome back to the series of AWS Cloudformation For Beginners 👨🏻‍💻. In this blog we create launch configuration along with security group and autoscaling group.

If you are a beginner and want to start your journey towards infra-as-code developer as part of your devops role buckle up 🚴‍♂️ and lets get started and understand core cloudformation concepts by implementing it...🎬

❗️❗️❗️ Pre-Requisite ❗️❗️❗️

1️⃣ Add visual studio code extension [Mandatory]

2️⃣ Adding VS Code Indentation Extension For Cloudformation Templates [Optional]

3️⃣ Deploy VPC, IGW & Associate [Mandatory]

4️⃣ Deploy only public subnet template from below blog [Mandatory].Make sure to create 2 public subnets

Parameters:  
  CustomVPC:
    Description: Select One VPC available in your existing account
    Type: AWS::EC2::VPC::Id
    Default: <"Your VPC ID">
  CustomInternetGateway:
    Description: Select One internet gateway available in your existing account
    Type: String
    Default: <"Your Internet Gateway ID">

Resources: 
  PublicSubnet1:
    Type: AWS::EC2::Subnet
    Properties:
      AvailabilityZone: "us-east-1a"
      MapPublicIpOnLaunch: true
      VpcId: !Ref CustomVPC
      CidrBlock: 10.0.0.0/25
      Tags:
        - Key: Name
          Value: PublicSubnet1
  PublicSubnet2:
    Type: AWS::EC2::Subnet
    Properties:
      AvailabilityZone: "us-east-1b"
      MapPublicIpOnLaunch: true
      VpcId: !Ref CustomVPC
      CidrBlock: 10.0.0.128/25

      Tags:
        - Key: Name
          Value: PublicSubnet2
  PublicRouteTable:
    Type: AWS::EC2::RouteTable
    Properties:
      VpcId: !Ref CustomVPC
      Tags:
        - Key: Name
          Value: PublicRouteTable
  PublicRoute:
    Type: AWS::EC2::Route
    Properties:
      RouteTableId: !Ref PublicRouteTable
      DestinationCidrBlock: 0.0.0.0/0
      GatewayId: !Ref CustomInternetGateway
  PublicSubnetRouteTableAssociation1:
    Type: AWS::EC2::SubnetRouteTableAssociation
    Properties:
      SubnetId: !Ref PublicSubnet1
      RouteTableId: !Ref PublicRouteTable
  PublicSubnetRouteTableAssociation2:
    Type: AWS::EC2::SubnetRouteTableAssociation
    Properties:
      SubnetId: !Ref PublicSubnet2
      RouteTableId: !Ref PublicRouteTable
Outputs:
  outputPublicSubnets1:
    Description: A reference to the created Public subnet
    Value: !Ref PublicSubnet1
    Export: 
      Name: PublicSubnet1
  outputPublicSubnets2:
    Description: A reference to the created Public subnet
    Value: !Ref PublicSubnet2
    Export: 
      Name: PublicSubnet2

🔊 To view double subnet github code click here

🎨 Diagrammatic Representation 🎨

image.png

🌟Deploy Auto Scaling Group With Launch Config🌟

In this we are going to create launch configuration for our autoscaling with properties Image ID and Instance Type as mandatory properties.
🔳 Parameters:-
PublicSubnets :- Using CommaDelimitedList parameters we can create a list of values of type string and pass it to arguments as a list.

Parameters:
  PublicSubnets:
    Type: CommaDelimitedList
    Description: The list of SubnetIds in your Virtual Private Cloud (VPC)
    Default: <subnet id 1>, <subnet id 2> #You can add multiple subnet ids here

🔳 Resources
ASGSecurityGroup:- Creating Security group and enabling ingress with http and ssh port.
➖ GroupName:- This property is used to mention security group name.
➖ GroupDescription:- This property is used to mention security group description and its mandatory property for this resource.
➖ SecurityGroupIngress:- This property is used to add ingress rules for [udp/tcp] ports enabled secured access to your resources.
➖ Tags:- One of the most important property used in all resources. Alaways make sure to attach tags for all your resources.
AsgConfig:- This resource is used to create pre-configured instance configuration which is later used by autoscaling group to deploy instances.
➖ ImageId:- This property is used to mention EC2 image ID based on which you want to launch your EC2 Instance.
➖ InstanceType:- This property is used to mention which type of instance you want to launch smal/medium/large based on your requirement.
➖ SecurityGroupIds:- This property is used to add list of security group you want to attach to your EC2 instance for enabling access control based on your security requirements.
➖ User Data: User data is user data/commands that you can specify at the time of launching your instance. These data/command executes after your EC2 instance starts. You don’t need to SSH into your EC2 instance and run those command one by one. Rather all you need is to specify the whole script in the user data section and they get executed once your instance boots up. You can use AWS CloudFormation to automatically install, configure, and start applications on Amazon EC2 instances. Doing so enables you to easily replicate deployments and update existing installations without connecting directly to the instance, which can save you a lot of time and effort.

Resources:
  ASGSecurityGroup:
    Type: AWS::EC2::SecurityGroup
    Properties:
      GroupName: AllowEC2TrafficForASG
      GroupDescription: Enable SSH access and HTTP access on the inbound port for launch configuration
      VpcId: <vpc id>  #Make sure this is same vpc id where your autoscaling group will launch
      SecurityGroupIngress:
        - IpProtocol: tcp
          FromPort: 80
          ToPort: 80
          CidrIp: 0.0.0.0/0
        - IpProtocol: tcp
          FromPort: 22
          ToPort: 22
          CidrIp: 0.0.0.0/0
      Tags:
        - Key: Name
          Value: ASGSecurityGroup
  AsgConfig:
    Type: AWS::AutoScaling::LaunchConfiguration
    Properties:
      InstanceType: t2.micro
      SecurityGroups:
      - !Ref ASGSecurityGroup
      ImageId: "ami-04505e74c0741db8d"
      UserData:
        Fn::Base64: 
          !Sub |
            #!/bin/bash
            sudo su
            sudo apt-get update -y
            sudo apt-get install -y apache2
            sudo ufw allow -y 'Apache'
            sudo systemctl start apache2
            sudo systemctl enable apache2
            echo Hello Viewers from $(hostname -f) > /var/www/html/index.html

AsgGroup:- This resource is used to launch autoscaling group to by using pre-defined launch configuration to achieve high availability.
➖ VPCZoneIdentifier:- Here you will have to define availability zones/subnetIds in which you want your instances to be launched and autoscaled.
➖ MinSize:- This is mandatory parameter and you need to define the min number of instances which should always be running as part of this autoscaling group.
➖ MaxSize:- This is mandatory parameter and you need to define the max number of instances till which autoscaling group can expand based on multiple scenarios.
➖ Tags:- One of the most important property used in all resources. Alaways make sure to attach tags for all your resources.

  AsgGroup:
    Type: AWS::AutoScaling::AutoScalingGroup
    Properties:
      VPCZoneIdentifier: !Ref PublicSubnets
      LaunchConfigurationName: !Ref AsgConfig
      MinSize: '1'
      MaxSize: '2'
      HealthCheckGracePeriod: 300
      MaxInstanceLifetime: 2592000
      Tags:
        - Key: Name
          Value: AsgGroup

🔳 Outputs: Its always a best practice to print output for your resources.
outputASGSecurityGroup:- Id of security group created for autoscaling launch configuration.
outputAsgConfig:- Id for autoscaling launch configuration.
outputAsgGroup:- Id for autoscaling group.

Outputs: 
  outputASGSecurityGroup: 
    Description: Id of security group created for autoscaling launch configuration
    Value: !Ref ASGSecurityGroup
  outputAsgConfig: 
    Description: Id for autoscaling launch configuration
    Value: !Ref AsgConfig
  outputAsgGroup: 
    Description: Id for autoscaling group
    Value: !Ref AsgGroup

🔊 To view github code click here

NACL.png

1️⃣ Lets validate our template 👨‍💻

aws cloudformation validate-template --template-body file://<file path>

2️⃣ After successful template verification lets create stack using our template 👨‍💻

aws cloudformation create-stack --stack-name asglaunchconfig --template-body file://<file path>

3️⃣ Check if the stack we created via template is completed successfully 👨‍💻

aws cloudformation list-stack-resources --stack-name asglaunchconfig

4️⃣ Describe stack and its resources to view its properties 👨‍💻

aws cloudformation describe-stacks --stack-name asglaunchconfig
aws cloudformation describe-stack-resources --stack-name asglaunchconfig

5️⃣ Check events for stack formation 👨‍💻

aws cloudformation describe-stack-events --stack-name asglaunchconfig

ELB (2).png

NACL (1).png

❗️❗️Important AWS Documentation To Be Viewed❗️❗️

⛔️ AWS::AutoScaling::LaunchConfiguration
⛔️ Supported AWS-specific parameter types
⛔️ AWS::AutoScaling::AutoScalingGroup
⛔️ AWS::EC2::SecurityGroup

🥁🥁 Conclusion 🥁🥁

In this blog I have covered 3 resources in which we will create
✦ Security group for Autoscaling.
✦ Launch Configuration for EC2 instances with Userdata.
✦ Autoscaling group deployment with launch configuration created.
I have used AWS CLI command to deploy these template and trust me AWS CLI is the realtime hero and I would suggest you to get acquainted towards it. Going forward I will be releasing further parts to this CloudFormation journey

📯Stay tuned for my next blog.....

🎊So, did you find my content helpful? If you did or like my other content, feel free to buy me a coffee. Thanks. 🎊

💫Cloudformation Series Sequence💫

🔰 Deploy VPC With Internet Gateway & Associate I
🔰 Public, Private Subnet & Route Table Creation & Association II
🔰 Private Subnet,Nat Gateway, Elastic Ip, Private Route Table & Associate III
🔰 NACL, Inbound & Outbound Routes, Security Group & Associate With Subnet IV
🔰 EC2 With Security Group & User Data & Mapping V
🔰 Target Group, Elastic Load Balancer & ELB Listener VI
🔰 Build Web Application Layer With AWS CloudFormation VII
🔰 Create Launch configuration along with Security group and AutoScaling group VIII

⌛️Realtime Usecases Cloudformation Templates⏳

💨 Schedule Automatic Detection Of Unused AWS EBS Volumes & Notify
💨 Schedule Automatic Detection Of Non Associated AWS Elastic IP's In AWS Account On Weekly Basis And Notify
💨 Schedule Automatic Deregistration Of AWS AMI On Weekly Basis And Notify

👨🏻‍💻Cloudformation Github Repository👨🏻‍💻

Did you find this article valuable?

Support Dheeraj Choudhary by becoming a sponsor. Any amount is appreciated!

See recent sponsors Learn more about Hashnode Sponsors
 
Share this