Instead of writing same resource block multiple times, create many with one block.
Creates same resource N times
locals {
project = "project-01"
}
resource "aws_subnet" "main" {
vpc_id = aws_vpc.my-vpc.id
count = 2 # create 2 subnets
cidr_block = "10.0.${count.index}.0/24" # index changes each time
tags = {
Name = "${local.project}-subnet-${count.index}"
}
}
count.index starts at 0:
index 0 → cidr: 10.0.0.0/24 name: project-01-subnet-0
index 1 → cidr: 10.0.1.0/24 name: project-01-subnet-1
Access by index:
aws_subnet.main[0].id # first subnet
aws_subnet.main[1].id # second subnet
aws_subnet.main[*].id # all subnet IDs as list