Define VPC CIDR Block Variable with CIDR Validation
Create a Terraform variable for VPC CIDR blocks with cidrhost() validation to ensure the value is a syntactically correct CIDR range.
Detailed Explanation
VPC CIDR Block Variable
Network CIDR blocks are fundamental to VPC design. A well-defined variable with validation prevents misconfigured network ranges that could cause routing issues or IP conflicts.
Variable Definition
variable "vpc_cidr" {
type = string
description = "CIDR block for the VPC"
default = "10.0.0.0/16"
validation {
condition = can(cidrhost(var.vpc_cidr, 0))
error_message = "Must be a valid CIDR block (e.g., 10.0.0.0/16)."
}
}
How can(cidrhost()) Works
The cidrhost() function calculates a specific host IP from a CIDR range. If the input isn't a valid CIDR, the function raises an error. Wrapping it in can() converts that error into a boolean:
can(cidrhost("10.0.0.0/16", 0))returnstruecan(cidrhost("not-a-cidr", 0))returnsfalse
This is the idiomatic Terraform pattern for CIDR validation without complex regex.
Common VPC CIDR Ranges
| Range | Size | Hosts | Use Case |
|---|---|---|---|
10.0.0.0/16 |
/16 | 65,534 | Large production VPCs |
10.0.0.0/20 |
/20 | 4,094 | Medium environments |
172.16.0.0/16 |
/16 | 65,534 | Separate network space |
192.168.0.0/24 |
/24 | 254 | Small dev/test VPCs |
Pairing with Subnet Variables
This variable often works alongside a subnet CIDR list variable. Ensure subnet CIDRs are subsets of the VPC CIDR:
variable "subnet_cidrs" {
type = list(string)
default = ["10.0.1.0/24", "10.0.2.0/24", "10.0.3.0/24"]
}
Use Case
VPC and networking modules where valid CIDR blocks must be enforced to prevent overlapping networks, routing failures, and peering conflicts.