Interview Prep/Real-World Interview/Write-Terraform tasks

Write a VPC with public and private subnets across 3 AZs using `count` or `for_each`.

IntermediateHands-onWrite-Terraform tasks
Answer
data "aws_availability_zones" "available" { state = "available" }

locals {
  azs = slice(data.aws_availability_zones.available.names, 0, 3)
}

resource "aws_vpc" "main" {
  cidr_block           = "10.0.0.0/16"
  enable_dns_hostnames = true
  tags = { Name = "main" }
}

resource "aws_subnet" "public" {
  for_each                = { for i, az in local.azs : az => i }
  vpc_id                  = aws_vpc.main.id
  availability_zone       = each.key
  cidr_block              = cidrsubnet(aws_vpc.main.cidr_block, 8, each.value)
  map_public_ip_on_launch = true
  tags = { Name = "public-${each.key}" }
}

resource "aws_subnet" "private" {
  for_each          = { for i, az in local.azs : az => i }
  vpc_id            = aws_vpc.main.id
  availability_zone = each.key
  cidr_block        = cidrsubnet(aws_vpc.main.cidr_block, 8, each.value + 10)
  tags = { Name = "private-${each.key}" }
}

Key trick → cidrsubnet("10.0.0.0/16", 8, n) returns 10.0.n.0/24. Keying for_each by AZ name means removing one AZ doesn't renumber and recreate the others, which is what happens with count.

All Real-World Interview questions Roadmap: Interview readiness

More on Write-Terraform tasks