Steps to Create VPC & Subnet Network Infrastructure on AWS Using Terraform

Hello, In this blog we are discussing how to create VPC ,Subnet, Route table & internet gateway on aws using Terraform. Terraform helps to create network infrastructure such as vpc, subnets, route table etc on aws console. It is an open source infrastructure setup tool, which is created by HashiCorp.

There are some steps to create VPC & Subnet using Terraform:

Step 1: Update the System.

apt-get update

Step 2: First Install Terraform on system so click on Link https://www.hackerxone.com/2021/05/06/how-install-configure-terraform-ubuntu/

  • Check terraform version.

terraform version

Step 3: Create a folder.

mkdir project

Step 4: To change the directory & Create a .tf file.

cd project

  • Create a file & write the terraform code to create VPC & Subnet  on AWS.

vim vpc.tf

  • Paste the following code:

provider "aws" {
region = "type-region"
access_key = "type_aws_access_key"
secret_key = "type_aws_secret_key"
}
resource "aws_vpc" "vpc" {
cidr_block = "10.0.1.0/24"
enable_dns_hostnames = true
tags = {
Name = "Test-vpc"
}
}
resource "aws_subnet" "public_sub" {
vpc_id = "${aws_vpc.vpc.id}"
cidr_block = "10.0.1.0/26"
availability_zone = "type_availability_zone"
tags = {
Name = "public_subnet"
}
}
resource "aws_internet_gateway" "gw" {
vpc_id = "${aws_vpc.vpc.id}"
tags = {
Name = "Test-igw"
}
}
resource "aws_route_table" "pub_rt" {
vpc_id = aws_vpc.vpc.id
tags = {
Name = "Test-pub-rt"
}
}
resource "aws_route" "route" {
route_table_id = "${aws_route_table.pub_rt.id}"
destination_cidr_block = "0.0.0.0/0"
gateway_id = "${aws_internet_gateway.gw.id}"
}
resource "aws_route_table_association" "rta" {
subnet_id = aws_subnet.public_sub.id
route_table_id = aws_route_table.pub_rt.id
}

Step 5: To Initialize the working directory.

terraform init

  • Here is the command output.

  • To check the configuration.

terraform plan

  • Here is the command output.

  • To verify the configuration.

terraform validate

  • Here is the command output.

[email protected]:/home/ubuntu/project# terraform validate
Success! The configuration is valid.

  • To run the code.

terraform apply

  • Here is the command output.

  • Type yes & Enter.

  • Finally, VPC & Subnet has been created.

Step 6: Open AWS Console.

  • Click on Services & select VPC.
  • Check created vpc.

  • Check created subnet.

  • Check created route table.

  • Check Internet gateway.

  • To delete the created network infrastructure.

terraform destroy

  • Here is the output.

  • Type yes & press enter.

  • Finally, Destroy completed.

Leave a Reply

Your email address will not be published.