Below is a simple example of a Terraform module for creating a VPC in AWS. The module is reusable and accepts input variables to customize the VPC configuration.
First, create a directory for your VPC module, e.g., modules/vpc
.
In the modules/vpc
directory, create a file named main.tf
and add the following contents:
resource "aws_vpc" "this" {
cidr_block = var.cidr_block
tags = {
Name = var.vpc_name
}
}
resource "aws_subnet" "this" {
count = length(var.subnet_cidr_blocks)
cidr_block = var.subnet_cidr_blocks[count.index]
vpc_id = aws_vpc.this.id
tags = {
Name = "${var.vpc_name}-subnet-${count.index + 1}"
}
}
resource "aws_internet_gateway" "this" {
vpc_id = aws_vpc.this.id
tags = {
Name = "${var.vpc_name}-igw"
}
}
resource "aws_route_table" "public" {
vpc_id = aws_vpc.this.id
tags = {
Name = "${var.vpc_name}-public-rt"
}
}
resource "aws_route" "public_internet_gateway" {
route_table_id = aws_route_table.public.id
destination_cidr_block = "0.0.0.0/0"
gateway_id = aws_internet_gateway.this.id
}
resource "aws_route_table_association" "public" {
count = length(var.subnet_cidr_blocks)
subnet_id = aws_subnet.this[count.index].id
route_table_id = aws_route_table.public.id
}
Next, create a file named variables.tf
in the same directory to define the input variables:
variable "cidr_block" {
description = "The CIDR block for the VPC"
type = string
}
variable "vpc_name" {
description = "The name of the VPC"
type = string
}
variable "subnet_cidr_blocks" {
description = "The list of CIDR blocks for the subnets"
type = list(string)
}
Now, to use the VPC module in your main Terraform configuration, create a main.tf
file at the root level and include the following contents:
module "vpc" {
source = "./modules/vpc"
cidr_block = "10.0.0.0/16"
vpc_name = "my-vpc"
subnet_cidr_blocks = ["10.0.1.0/24", "10.0.2.0/24", "10.0.3.0/24"]
}
This configuration sets up a VPC with a /16 CIDR block, an Internet gateway, a public route table, and three /24 subnets. The module is reusable and can be customized using input variables.
Please note that this is just a simple example, and a production-ready VPC module may include additional resources such as network ACLs, security groups, and NAT gateways.