Interview Prep/Terraform/Resources Variables and Expressions

You need to split a /16 into subnets across 3 AZs without hand-computing CIDRs. What function do you use?

BeginnerScenarioResources Variables and Expressions
Answer

Situation read → Network math is error-prone by hand.

What I'd do →

locals {
  azs = slice(data.aws_availability_zones.available.names, 0, 3)
  private_subnets = [for i, az in local.azs : cidrsubnet(var.vpc_cidr, 8, i)]
  public_subnets  = [for i, az in local.azs : cidrsubnet(var.vpc_cidr, 8, i + 100)]
}

Test it first with terraform console: cidrsubnet("10.0.0.0/16", 8, 1) gives 10.0.1.0/24.

Why → cidrsubnet(prefix, newbits, netnum) is deterministic, so subnets never overlap and never change between runs.

Interview tip → Leave gaps in the numbering for future tiers.

All Terraform questions Roadmap: Terraform

More on Resources Variables and Expressions