Terraform generate subnet CIDR using network function

How cidrsubnet works in Terraform | by Nadeen Nilanka | Medium

Need an easy and simple way to create the subnet CIDR that adhere the specific pattern such as even number for public subnet, odd number for private subnet.

Look no further than the cidrsubnet() function along with a for loop and the range function! By providing a range to the cidrsubnet() function, the function automatically generates subnets based on the number of bits you’d like to step:

cidrsubnet(prefix, newbits, netnum)

This allows you to generate subnets quickly without complicated custom functions or other external resources. With the right range function attributes (in this case, odd and even numbers), you can also prevent collisions. If I were to set a limit of 255, I could produce the entire subnet range for a /24 with one line!

provider "aws" {
  region = "ap-southeast-1"

variable "vpc_cidr" {
  type    = string
  default = ""

locals {
  private_subnet_cidr = [for i in range(1, 6, 2) : cidrsubnet(var.vpc_cidr, 8, i)]
  public_subnet_cidr  = [for i in range(2, 7, 2) : cidrsubnet(var.vpc_cidr, 8, i)]

resource "aws_vpc" "main_vpc" {
  cidr_block       = var.vpc_cidr
  instance_tenancy = "default"
  tags = {
    Name  = "Demo-VPC"

resource "aws_subnet" "private_subnet" {
  count      = length(local.private_subnet_cidr)
  vpc_id     = aws_vpc.main_vpc.id
  cidr_block = local.private_subnet_cidr[count.index]
  tags = {
    Name  = "Private Subnet ${count.index + 1}"

resource "aws_subnet" "public_subnet" {
  count      = length(local.public_subnet_cidr)
  vpc_id     = aws_vpc.main_vpc.id
  cidr_block = local.public_subnet_cidr[count.index]
  tags = {
    Name  = "Public Subnet ${count.index + 1}"

In this demo, I will set my VPC CIDR to, which it’s can allocate around 65,536 ips. I will create 2 local variable to set the private and public subnet CIDR range, use the for loop and cidrsubnet function to create the list.

Lastly, use the aws_subnet block to create the subnet by loop through the local.private_subnet_cidr and local.public_subnet_cidr.

Initialise and deploy the code:

$ terraform init
$ terraform apply --auto-approve

Login to AWS VPC console, and check for the subnet which just newly deploy and I can see there are total of 6 subnet with the CIDR as per expected.

Clean up the demo resource:

$ terraform destroy --auto-approve

To know more about Terraform cidrsubnet fucntion: https://www.terraform.io/docs/configuration/functions/cidrsubnet.html

Leave a Reply

google.com, pub-3772983857049267, DIRECT, f08c47fec0942fa0
%d bloggers like this: