Define Subnet CIDRs as a List Variable

Create a Terraform list(string) variable for subnet CIDR blocks with validation ensuring at least one subnet is defined.

Networking

Detailed Explanation

Subnet CIDRs List Variable

Subnet definitions are one of the most common list variables in Terraform networking modules. Each CIDR block in the list typically maps to a subnet in a different availability zone.

Variable Definition

variable "subnet_cidrs" {
  type        = list(string)
  description = "List of CIDR blocks for subnets"
  default     = ["10.0.1.0/24", "10.0.2.0/24", "10.0.3.0/24"]

  validation {
    condition     = length(var.subnet_cidrs) > 0
    error_message = "At least one subnet CIDR block must be provided."
  }
}

Separate Public and Private Subnets

A common pattern uses two list variables:

variable "public_subnet_cidrs" {
  type        = list(string)
  description = "CIDR blocks for public subnets (with internet gateway)"
  default     = ["10.0.1.0/24", "10.0.2.0/24"]
}

variable "private_subnet_cidrs" {
  type        = list(string)
  description = "CIDR blocks for private subnets (NAT gateway only)"
  default     = ["10.0.10.0/24", "10.0.11.0/24"]
}

Using with for_each

resource "aws_subnet" "public" {
  for_each = toset(var.public_subnet_cidrs)

  vpc_id     = aws_vpc.main.id
  cidr_block = each.value
}

CIDR Planning Tips

VPC CIDR Subnet Mask Subnets Hosts per Subnet
/16 /20 16 4,094
/16 /24 256 254
/20 /24 16 254
/24 /28 16 14

Plan your subnet CIDRs to leave room for growth. AWS reserves 5 IP addresses per subnet, so a /24 gives 251 usable hosts.

Use Case

VPC modules that create subnets across availability zones, where the number and size of subnets varies between environments (fewer in dev, more in production).

Try It — Terraform Variable Generator

Open full tool