#count-vs-for-each
What is the difference between `count` and `for_each`? Which do you pick in new code?
Что отвечать
`count = N` creates N identical resources at addresses `r[0]`, `r[1]`, `r[2]`. `for_each = set/map` creates one resource per element at addresses `r["alpha"]`, `r["beta"]`. The main difference is in state. Delete an element from the middle of a count list and everything after it shifts down one index and gets recreated. With for_each over a map, delete a key and only that one resource goes away. In new code it is almost always `for_each`. count stays for the "N of the same kind, no identity" case (letters of the alphabet, array indexes).
Что хотят услышать
The candidate should: - explain why for_each is safer on reindexing: stable keys instead of positional ones - note that for_each needs a set(string) or a map; a list has to be wrapped in `toset(list)` - say that for_each keys must be known at plan time, so `for_each = aws_subnet.x[*].id` is not allowed but `for_each = var.subnets` is - separate `each.key` and `each.value` for a map (key and value); for a set both equal the element - mention `for_each = { for k, v in var.users : k => v if v.enabled }` as the idiomatic filter
Подводные камни
- ✗ Using count with a list whose length changes. Deleting an element from the middle recreates the tail
- ✗ Passing a list to for_each with `for_each = var.list`. That is a type error, you need `toset(var.list)` or a map
- ✗ Running for_each over a computed value (`aws_subnet.x[*].id`). The plan fails with 'cannot use unknown value'
Follow-up
- ? What happens when you delete the 5th element from a list under `count`?
- ? How do you build a map-based for_each over computed values?
- ? When is `count` actually more sensible than `for_each`?
Глубина в базе знаний