Software Engineering

Create Internet Gateway & Assign to EC2 in CloudFormation

To create an Internet Gateway and associate it with an EC2 instance using AWS CloudFormation, you can follow these steps:

Step 1: Create a CloudFormation template

Create a new YAML or JSON file with a .yaml or .json extension (e.g., template.yaml), and add the following contents:

AWSTemplateFormatVersion: "2010-09-09"
    Type: AWS::EC2::VPC
      CidrBlock:  # Replace with your desired VPC CIDR block

    Type: AWS::EC2::InternetGateway

    Type: AWS::EC2::VPCGatewayAttachment
      VpcId: !Ref MyVPC
      InternetGatewayId: !Ref MyInternetGateway

    Type: AWS::EC2::Subnet
      VpcId: !Ref MyVPC
      CidrBlock:  # Replace with your desired subnet CIDR block
      AvailabilityZone: us-west-2a  # Replace with your desired availability zone

    Type: AWS::EC2::RouteTable
      VpcId: !Ref MyVPC

    Type: AWS::EC2::Route
    DependsOn: MyVPCGatewayAttachment
      RouteTableId: !Ref MyRouteTable
      GatewayId: !Ref MyInternetGateway

    Type: AWS::EC2::Instance
      ImageId: ami-0123456789abcdef0  # Replace with your desired AMI ID
      InstanceType: t2.micro  # Replace with your desired instance type
      SubnetId: !Ref MySubnet

Make sure to replace the placeholder values (CidrBlock, AvailabilityZone, ImageId, etc.) with your desired values.

Step 2: Create a CloudFormation stack

  1. Open the AWS Management Console and navigate to the CloudFormation service.
  2. Click on “Create stack” or “Create a new stack” to start the stack creation process.
  3. Choose “Upload a template file” and select the CloudFormation template file you created in Step 1.
  4. Proceed through the wizard, providing a stack name and any additional configuration options as needed.
  5. Review the stack details and click on “Create stack” to start the stack creation process.

CloudFormation will now create the internet gateway, VPC, subnet, route table, and EC2 instance according to the template.

Once the stack creation process completes, your infrastructure will be provisioned, and the EC2 instance will be associated with the internet gateway.

It’s important to have a basic understanding of CloudFormation and AWS concepts when working with CloudFormation templates. Additionally, ensure that you have appropriate permissions and a properly configured AWS account to create the required resources.