AWS VPC Public Private Subnets Terraform Resources

Github : https://github.com/NadunOvitigala/aws-vpc-public-private-subnets-terraform-resources/tree/main

Clone the git repository and run,

$ terraform init
$ terraform plan
$ terraform apply --auto-approve

Code Explain

Select your region to deploy VPC

provider "aws" {
    region = "ap-south-1"
}

Choose name and CIDR block

resource "aws_vpc" "cloudhats" {
    cidr_block = "10.0.0.0/16"

    tags = {
        Name = "cloudhats"
    }
}

Creating public subnet

resource "aws_subnet" "public" {
    vpc_id = aws_vpc.cloudhats.id 
    cidr_block = "10.0.0.0/24"

    tags = {
        Name = "public subnet"
    }
}

Creating private subnet

resource "aws_subnet" "private" {
    vpc_id     = aws_vpc.cloudhats.id
    cidr_block = "10.0.1.0/24"

    tags = {
        Name = "private subnet"
    }
}

Creating internet gateway to access internet

resource "aws_internet_gateway" "igw" {
    vpc_id = aws_vpc.cloudhats.id
    
    tags = {
        Name = "igw"
    }
}

Allocate elastic ip for nat gateway

resource "aws_eip" "nat_eip" {
    vpc = true
    depends_on = [aws_internet_gateway.igw]

    tags = {
        Name = "nat_eip"
    }
}

Creating nat gatway

resource "aws_nat_gateway" "nat" {
    allocation_id = aws_eip.nat_eip.id
    subnet_id     = aws_subnet.public.id

    tags = {
        Name = "nat"
    }

}

Creating route internet gateway to public subnet

resource "aws_route_table" "public" {
    vpc_id = aws_vpc.cloudhats.id

    route {
        cidr_block = "0.0.0.0/0"
        gateway_id = aws_internet_gateway.igw.id
    }

    tags = {
        Name = "public route"
    }
}

resource "aws_route_table_association" "public" {
    subnet_id      = aws_subnet.public.id
    route_table_id = aws_route_table.public.id
}

Creating route public subnet to private subnet for getting internet access

resource "aws_route_table" "private" {
    vpc_id =aws_vpc.cloudhats.id

    route {
        cidr_block = "0.0.0.0/0"
        gateway_id = aws_nat_gateway.nat.id
    }

    tags = {
        Name = "private route"
    }
}

resource "aws_route_table_association" "private" {
    subnet_id      = aws_subnet.private.id
    route_table_id = aws_route_table.private.id
}

That’s it.
Thanks.

Leave a Comment

Your email address will not be published. Required fields are marked *