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.
More on Write-Terraform tasks
Write Terraform for an S3 bucket with versioning, encryption and public access blocked.BeginnerWrite the remote backend configuration with S3 and state locking.BeginnerWrite a reusable module for an EC2 instance with inputs, outputs and validation.AdvancedWrite a security group that allows HTTPS from anywhere and SSH only from an office CIDR.BeginnerCreate multiple IAM users from a list with `for_each`, and output their ARNs as a map.BeginnerWrite Terraform that looks up an existing VPC by tag instead of hardcoding its ID.Intermediate