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
.json extension (e.g.,
template.yaml), and add the following contents:
AWSTemplateFormatVersion: "2010-09-09" Resources: MyVPC: Type: AWS::EC2::VPC Properties: CidrBlock: 10.0.0.0/16 # Replace with your desired VPC CIDR block MyInternetGateway: Type: AWS::EC2::InternetGateway MyVPCGatewayAttachment: Type: AWS::EC2::VPCGatewayAttachment Properties: VpcId: !Ref MyVPC InternetGatewayId: !Ref MyInternetGateway MySubnet: Type: AWS::EC2::Subnet Properties: VpcId: !Ref MyVPC CidrBlock: 10.0.0.0/24 # Replace with your desired subnet CIDR block AvailabilityZone: us-west-2a # Replace with your desired availability zone MyRouteTable: Type: AWS::EC2::RouteTable Properties: VpcId: !Ref MyVPC MyDefaultRoute: Type: AWS::EC2::Route DependsOn: MyVPCGatewayAttachment Properties: RouteTableId: !Ref MyRouteTable DestinationCidrBlock: 0.0.0.0/0 GatewayId: !Ref MyInternetGateway MyEC2Instance: Type: AWS::EC2::Instance Properties: 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 (
ImageId, etc.) with your desired values.
Step 2: Create a CloudFormation stack
- Open the AWS Management Console and navigate to the CloudFormation service.
- Click on “Create stack” or “Create a new stack” to start the stack creation process.
- Choose “Upload a template file” and select the CloudFormation template file you created in Step 1.
- Proceed through the wizard, providing a stack name and any additional configuration options as needed.
- 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.