0
0
TerraformHow-ToBeginner · 3 min read

How to Use cidrsubnet Function in Terraform

The cidrsubnet function in Terraform takes a base CIDR block and creates a new subnet by adding bits to the network prefix. You provide the base CIDR, the number of new bits to add, and a subnet number to get a new subnet CIDR block.
📐

Syntax

The cidrsubnet function has three parts:

  • base_cidr: The original CIDR block (like "10.0.0.0/16")
  • newbits: Number of bits to add to the prefix to create subnets
  • netnum: The subnet number to select (starting at 0)

The function returns a new CIDR block string representing the subnet.

terraform
cidrsubnet(base_cidr, newbits, netnum)
💻

Example

This example shows how to create four /18 subnets from a /16 base CIDR block using cidrsubnet. It demonstrates how subnet numbers select different subnets.

terraform
variable "base_cidr" {
  default = "10.0.0.0/16"
}

output "subnet_0" {
  value = cidrsubnet(var.base_cidr, 2, 0)  # Adds 2 bits, subnet 0
}

output "subnet_1" {
  value = cidrsubnet(var.base_cidr, 2, 1)  # Adds 2 bits, subnet 1
}

output "subnet_2" {
  value = cidrsubnet(var.base_cidr, 2, 2)  # Adds 2 bits, subnet 2
}

output "subnet_3" {
  value = cidrsubnet(var.base_cidr, 2, 3)  # Adds 2 bits, subnet 3
}
Output
subnet_0 = "10.0.0.0/18" subnet_1 = "10.0.64.0/18" subnet_2 = "10.0.128.0/18" subnet_3 = "10.0.192.0/18"
⚠️

Common Pitfalls

Common mistakes when using cidrsubnet include:

  • Adding too many bits causing subnet prefix length to exceed 32 (IPv4) or 128 (IPv6).
  • Using a netnum that is too large for the number of subnets possible with the added bits.
  • Confusing newbits with the total prefix length instead of bits to add.

Always check that newbits + original prefix length does not exceed the max prefix length.

terraform
/* Wrong: newbits too large (adds 20 bits to /16, total 36 > 32) */
output "invalid_subnet" {
  value = cidrsubnet("10.0.0.0/16", 20, 0)
}

/* Right: newbits within limit (adds 4 bits to /16, total 20) */
output "valid_subnet" {
  value = cidrsubnet("10.0.0.0/16", 4, 0)
}
📊

Quick Reference

ParameterDescriptionExample
base_cidrThe starting CIDR block"10.0.0.0/16"
newbitsNumber of bits to add to prefix2
netnumSubnet number (0-based index)0, 1, 2, ...
ReturnNew subnet CIDR block string"10.0.64.0/18"

Key Takeaways

Use cidrsubnet(base_cidr, newbits, netnum) to create subnet CIDRs by adding bits to the base prefix.
Ensure newbits plus original prefix length does not exceed 32 for IPv4 or 128 for IPv6.
Subnet numbers (netnum) start at 0 and select which subnet you want from the new bits added.
Common errors include adding too many bits or using invalid subnet numbers.
cidrsubnet helps divide a large network block into smaller subnet blocks easily in Terraform.