Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass CIDR range for subnets using cidrsubnets to VPC module in Terraform Version 0.14

Terraform cidrsubnets gives me the following subnets which is what I want.

Terraform Version I am using: Terraform v0.14.9

> cidrsubnets("172.16.0.0/18", 6, 6, 6, 6)
tolist([
  "172.16.0.0/24",
  "172.16.1.0/24",
  "172.16.2.0/24",
  "172.16.3.0/24",
])
Requirement
==========
Main CIDR range = 172.16.0.0/18
Public Subnets = [172.16.0.0/24, 172.16.1.0/24]
Private Subents = [172.16.2.0/24, 172.16.3.0/24]

How can I pass the above CIDR ranges for public and private subnets using Terraform cidrsubnets function to the below VPC module.

variable "vpc_cidr" {
  default = "172.16.0.0/18"
}

data "aws_availability_zones" "azs" {
  state = "available"
}

module "vpc" {
  
  source  = "terraform-aws-modules/vpc/aws"
  version = "2.77.0"

  name                 = "my-vpc"
  cidr                 = var.vpc_cidr
  azs                  = data.aws_availability_zones.azs.names
  private_subnets      = ["172.16.1.0/24", "172.16.2.0/24"] <= I want to pass these subnets from cidrsubnets function
  public_subnets       = ["172.16.3.0/24", "172.16.4.0/24"] <= I want to pass these subnets from cidrsubnets function
  enable_nat_gateway   = true
  single_nat_gateway   = true
  enable_dns_hostnames = true

}


Can someone help me with this, please?

like image 558
Jwary Avatar asked Oct 31 '25 07:10

Jwary


1 Answers

You could use slice function on top of the cidrsubnets one. Since cidrsubnets will return a list, slice it up according to the index and you'll have 2 lists with public and private IPs as requested:

module "vpc" {
  ...
  private_subnets      = slice(cidrsubnets(var.vpc_cidr, 6, 6, 6, 6),0,2)
  public_subnets       = slice(cidrsubnets(var.vpc_cidr, 6, 6, 6, 6),2,4)
  ...
}

like image 173
Styszma Avatar answered Nov 02 '25 21:11

Styszma