AWS CIDR using CloudFormation and Terraform

Fei Yao
2 min readJul 23, 2018

--

Using CloudFormation (CFN) or Terraform (TF) as the Cloud Orchestration tool has become the de facto way of doing Infrastructure-as-Code (IaC) in modern cloud infrastructure. Subnets are the basic building blocks of VPC. Traditionally, you can use variables to assign those CIDRs when the infrastructure is small, but quickly it becomes messy. There is a better way of doing it, more elegant and managable.

Photo by Leo Roomets on Unsplash

CloudFormation gives you Fn::Cidr intrinsic function, where Terrafrom has cidrsubnet interpolation. We’ll create a 10.0.0.0/23 VPC with 512 IP addresses.We will equally this space divide into 6 subnets with 64 IP addresses each which gives us /26 CIDR block.

The above CFN snippet will give us a desired result. Here is the break down of the function:

Fn::Cidr: [ ipBlock, count, sizeMask ]

Both ipBlock, and count are self explanatory. What is sizeMask? In CIDR, notation subnet mask is used to identify subnet address by performing a bitwise AND operation. For example, subnet mask 255.255.255.0 is 11111111.11111111.11111111.00000000 in binary. This addes up to 24 1’s or /24. If we need /26, the binary form becomes 11111111.11111111.11111111.11000000 and it is equivalent to 255.255.255.192. The sizeMask is 32 - 26 = 6. Hence, using the intrinsic function becomes:

Fn::Cidr: [ "10.0.0.0/23", "6", "6" ]

Terraform has the similar function to ease the subnet CIDR assigning.

cidrsubnet(iprange, newbits, netnum)

Using Terraform Console can easily verify the desired outcome.

➜  ~ terraform console
> cidrsubnet("10.0.0.0/23", 3, 0)
10.0.0.0/26
> cidrsubnet("10.0.0.0/23", 3, 1)
10.0.0.64/26
> cidrsubnet("10.0.0.0/23", 3, 2)
10.0.0.128/26
> cidrsubnet("10.0.0.0/23", 3, 3)
10.0.0.192/26
> cidrsubnet("10.0.0.0/23", 3, 4)
10.0.1.0/26
> cidrsubnet("10.0.0.0/23", 3, 5)
10.0.1.64/26
>

Both above mentioned CFN and TF methods deliver the same result. Since AWS reserves 5 IP addresses per subnet you only get 59 as the result for /26 block.

Subnet CIDR

--

--