You manage subnets from a list of CIDRs. Someone removes the second CIDR and Terraform plans to recreate the third subnet. Why, and what do you change?
IntermediateScenarioResources Variables and Expressions
Answer
Situation read → count keyed by list index; the list shifted.
What I'd do →
- Switch to
for_eachover a map keyed by a stable name. - Add
movedblocks to avoid recreating existing subnets.
variable "subnets" {
type = map(string) # { a = "10.0.1.0/24", b = "10.0.2.0/24" }
}
resource "aws_subnet" "this" {
for_each = var.subnets
vpc_id = aws_vpc.main.id
cidr_block = each.value
}
Why → Keys are identities. Removing key b only affects b.
Interview tip → Choose keys that never change (names, not IPs).
More on Resources Variables and Expressions
You need three identical web servers. How do you declare them, and what is the catch with `count`?BeginnerHow do you stop someone passing `environment = "production"` when only `dev`, `stage` and `prod` are valid?BeginnerA module takes a database password and exposes the connection string as an output. How do you stop them leaking into plan output?BeginnerA monitoring stack should only exist in prod. How do you create a resource conditionally?BeginnerYou have subnets defined as `{ web = {...}, db = {...} }` per VPC, nested two levels deep. How do you create them with `for_each`?AdvancedA security group needs 15 ingress rules read from a variable. How do you avoid 15 copy-pasted blocks?Intermediate