Steps To Create AWS VPC Using Terraform
Step 1: First mention the provider and region in which you want to create VPC.
provider.tf
provider "aws" {
region = "us-east-1"
}
Step 2 : Create a VPC . Here mention the CIDR block and give a name to the VPC .
create_vpc.tf
resource "aws_vpc" "main" {
cidr_block = "10.0.0.0/16"
instance_tenancy = "default"
tags = {
Name = "vpc"
}
}
Step 3 : Then create a subnet inside the VPC .
subnet.tf
resource "aws_subnet" "main" {
vpc_id = aws_vpc.main.id
cidr_block = "10.0.1.0/24"
map_public_ip_on_launch=true
tags = {
Name = "Public-Subnet"
}
}
Step 4 : But the subnet is isolated now . If you create an EC2 instance inside this subnet then you can not connect the EC2 instance as it is present in an isolated environment . So you need an internet gateway .
internet_gateway.tf
resource "aws_internet_gateway" "igw" {
vpc_id = aws_vpc.main.id
tags = {
Name = "IGW"
}
}
Step 5 : Create a route table and associate the route table with subnet . Here in the route all the traffic is passed through internet gateway .
route_table.tf
resource "aws_route_table" "rt" {
vpc_id = aws_vpc.main.id
route {
cidr_block = "0.0.0.0/0"
gateway_id = aws_internet_gateway.igw.id
}
tags = {
Name = "route_table"
}
}
route_subnet_association.tf
resource "aws_route_table_association" "a" {
subnet_id = aws_subnet.main.id
route_table_id = aws_route_table.rt.id
}
Step 6 : After this execute all these terraform files using the below commands one by one .
terraform init
terraform plan
terraform apply
Step 7: Check on your AWS console whether the VPC is created or not
Now if you want to delete all the resources created through terraform , then write this command .
terraform destroy
How To Create AWS VPC Using Terraform ?
Terraform is an IAAC tool used to automate programmatic infrastructure provisioning. Here in this guide, I will first discuss what is AWS VPC. Then I will discuss terraform. After this, I will walk you through the different steps to write a code using Terraform to create a custom AWS VPC using subnet, internet gateway, and routing tables.