DEV Community

Cover image for Step by step guide to launch EC2 instance in a VPC using cloud formation
Uwadone Joshua
Uwadone Joshua

Posted on

Step by step guide to launch EC2 instance in a VPC using cloud formation

Architectural Diagram of Deploying EC2 in a Custom-made VPC using Cloud Formation

Infrastructure as Code (IaC): is a practice of managing and provisioning infrastructure through code instead of manual processes. By treating infrastructure as code, organizations can automate the creation, modification, and deletion of infrastructure resources, such as servers, networks, and storage e.t.c.

Problems Solved by IaC:

Manual Error Reduction:

  • Consistency: IaC ensures that infrastructure is provisioned consistently, reducing the risk of human error.
  • Repeatable Deployments: IaC scripts can be run multiple times to create identical environments.

Increased Efficiency:

  • Automation: IaC automates the provisioning process, saving time and effort.
  • Faster Time to Market: Infrastructure can be deployed quickly and efficiently.

Improved Collaboration:

  • Control: IaC uses version control systems like Git to track changes, enabling collaboration and rollback.
  • Shared Understanding: Code-based infrastructure is easier to understand and collaborate on.

Enhanced Security:

  • Configuration Drift Prevention: IaC helps maintain consistent configurations, reducing security vulnerabilities.
  • Auditing and Compliance: IaC provides a clear audit trail for compliance and security audits.

Popular IaC Tools:
Terraform: A popular open-source tool for managing infrastructure across multiple cloud providers.
Ansible: A configuration management tool that can be used for infrastructure automation.
Puppet: A configuration management tool for automating server and system administration tasks.
Chef: A configuration management tool for automating infrastructure and applications.
AWS Cloud Formation: This is an infrastructure-as-code tool that defines resources and their configurations in a standardized template -- either a JavaScript Object Notation (JSON) or YAML format. In general, YAML is the preferable option, as it's more concise; JSON requires a much higher number of characters. YAML also supports the ability to add comments, which JSON does not.

By adopting IaC, organizations can significantly improve their infrastructure management practices, reduce operational costs, and accelerate application delivery.

Alright! Let’s dive right into how to launch an EC2 instance in a VPC using AWS CloudFormation.

This guide covers creating a basic CloudFormation stack to provision a VPC, subnets, security groups, and an EC2 instance.

Step 1: Prepare Your CloudFormation Template

So the next thing we will need to do is, we’ll want to do is to create a CloudFormation template file (in YAML format) named ec2_vpc.yaml.

We will be using the below template to create an EC2 Instance by replacing the following defaults of SubnetId, SecurityGroupId, and ImageId with actual values that exist


`AWSTemplateFormatVersion: 2010-09-09
Description: My first Cloud Formation Template with YAML comments.

Resources:
  MyVPC:
    Type: AWS::EC2::VPC
    Properties:
      CidrBlock: 10.0.0.0/16
      Tags:
        - Key: Name
          Value: MyVPC

  PublicSubnet:
    Type: AWS::EC2::Subnet
    Properties:
      CidrBlock: 10.0.1.0/24
      VpcId: !Ref MyVPC
      MapPublicIpOnLaunch: true
      Tags:
        - Key: Name
          Value: PublicSubnet

  InternetGateway:
    Type: AWS::EC2::InternetGateway
    Properties:
      Tags:
        - Key: Name
          Value: MyInternetGateway`

`AttachGateway:
    Type: AWS::EC2::VPCGatewayAttachment
    Properties:
      VpcId: !Ref MyVPC
      InternetGatewayId: !Ref InternetGateway

  PublicRouteTable:
    Type: AWS::EC2::RouteTable
    Properties:
      VpcId: !Ref MyVPC
      Tags:
        - Key: Name
          Value: PublicRouteTable

  PublicRoute:
    Type: AWS::EC2::Route
    Properties:
      RouteTableId: !Ref PublicRouteTable
      DestinationCidrBlock: 0.0.0.0/0
      GatewayId: !Ref InternetGateway

  SubnetRouteTableAssociation:
    Type: AWS::EC2::SubnetRouteTableAssociation
    Properties:
      SubnetId: !Ref PublicSubnet
      RouteTableId: !Ref PublicRouteTable`

 `MySecurityGroup:
    Type: AWS::EC2::SecurityGroup
    Properties:
      GroupDescription: Allow SSH and HTTP access
      VpcId: !Ref MyVPC
      SecurityGroupIngress:
        - IpProtocol: tcp
          FromPort: 22
          ToPort: 22
          CidrIp: 0.0.0.0/0
        - IpProtocol: tcp
          FromPort: 80
          ToPort: 80
          CidrIp: 0.0.0.0/0
        - IpProtocol: tcp
          FromPort: 443
          ToPort: 443
          CidrIp: 0.0.0.0/0
      Tags:
        - Key: Name
          Value: MySecurityGroup`

`MyEC2Instance:
    Type: AWS::EC2::Instance
    Properties:
      InstanceType: t2.micro
      KeyName: EC2-CTF-VPC  # Ensure this key pair exists in your AWS account
      ImageId: ami-06b21ccaeff8cd686  # Confirm this is valid for your target region
      NetworkInterfaces:
        - AssociatePublicIpAddress: true
          SubnetId: !Ref PublicSubnet
          DeviceIndex: 0
          GroupSet:
            - !Ref MySecurityGroup
      Tags:
        - Key: Name
          Value: MyEC2Instance
`

Enter fullscreen mode Exit fullscreen mode

Image description

Image description

Image description

Image description

Step 2: Create the CloudFormation Stack:
After you input your login details, you will be brought to the dashboard, observe the search button at the top.

Image description

Next we’ll click on the search bar, and type “CLOUD FORMATION” you will see the Cloudformation resource as shown below.

Image description

When you clicked on the Cloudformation, you will be brought to the cloudformation dashboard, click on the “Create Stack"

Image description

Creating a New Stack, inside the stack section, you will see 3 options: “Choose an existing template, Use a sample template and Build from Infrastructure Composer.”
But for the sake of this projec, we will select the first option “Choose an existing template”.
Scroll down and specify the template to choose the file from.

Image description

We will choose the “upload a template file” option. Then click on choose file to upload our YAML file from our local machine.

Image description

Upload your ec2_vpc.yaml template file from your computer. Select the file and click open.

Image description

As seen below, after uploading your preferred file, click the next button

Image description

Next would be to enter a Stack name (e.g., EC2InVPCStack) and click on the next button.

Image description

Configure Stack Options: Choose any additional options if necessary (tags, permissions, etc.), or leave as default. We will give our stack a tag key-value pair as shown below and scroll down.

Image description

And leave the rest as default and click next.

Image description

Review and Create Stack: Review the details and check if all the configurations are set properly.

Image description

If everything is properly set, click on the ‘submit’ button.

Image description

Step 3: Wait for the Stack to Complete: CloudFormation will begin creating the resources. You can monitor the progress in the “Events” tab.

Image description

When the ‘Status’ shows CREATE_COMPLETE, your EC2 instance and VPC and other resources have been successfully launched.

Image description

Step 4: Verify the Resources

View Resources in CloudFormation:

  • In the CloudFormation console, select your stack and go to the Resources tab to see the created resources.

Image description

Check in EC2 and VPC Consoles:

  • Go to the EC2 console to see the running instance.

Image description

  • Go to the VPC console to verify the VPC, subnet, and security group.

Image description

This template creates a basic setup with a VPC, subnet, internet gateway, route table, security group, and an EC2 instance. You can customize the configurations further based on your requirements.

I also want to express that your feedback is always welcome. As I strive to provide accurate information and insights, I acknowledge that there’s always room for improvement. If you notice any mistakes or have suggestions for enhancement, I sincerely invite you to share them with me.

🤩 Thanks for being patient and following me. Keep supporting 🙏
Share a reaction 👏 if you liked this article.

For more exercises — please follow me below ✅!
https://dev.to/uwadon1

Top comments (0)