Hashicorp’s cidrsubnet function

A while back I witnessed a Terraform presentation where a subnet’s IPv4 CIDR block was constructed from a parent VCN by invoking a Hashicorp function called cidrsubnet. This function is very useful because it can save time when you have multiple VCNs in your Terraform code. And it is universal, it can be used when there are several concurrent Terraform providers in the same code.

The function’s format is like this: cidrsubnet(prefix, newbits, netnum).

The prefix field is for the VCN CIDR. You can enter a variable in the prefix field. For example cidrsubnet(var.vcn_cidr, 8,1). Let’s say that the VCN CIDR is 10.0.0.0/16, then the value of var.vcn_cidr is 10.0.0.0/16. So, the function looks like this: cidersubnet(“10.0.0.0/16”,8,1).

The newbits value is the number of digits that you will be adding to the actual CIDR value. 16 + 8 = 24, so the subnet will be a /24 subnet.

The netnum value is for completing the actual subnet, and it depicts the “raw” decimal number of the binary portion of the subnet side of the CIDR, in this case is the third octet. The result for the subnet is 10.0.1.0/24.

This example illustrates it better:

cidrsubnet(“10.1.2.0/24”, 4, 15). 24+4 = 28, so the subnet will be a x.x.x.x/28 subnet.

The value in the netnum field will help us identify which of the 16 possible /28 subnets we’re creating. On a /28 subnet, in the fourth octet, the four left bits are the subnetwork bits. Convert 15 (the netnum value) to binary and you will get 1111. Place it on the subnetwork side of the fourth octet and you will get 1111|0000. The decimal value of the whole octet is 240, therefore the subnet is 10.1.2.240/28.

This is optimal, isn’t it?