for_each
What is for_each?
for_each: Creates one instance per element of a map or set. Instances are keyed by name, so adding/removing is stable. for_each creates one instance of a resource for each item in a map or set. Each instance is identified by its key, such as aws_iam_user.u["alice"], rather than by a number. That key-based identity is the reason to prefer it over count for collections. Removing "alice" from the set removes only Alice's user. With count, removing the first item would shift every other item and cause unnecessary replacements.
Frequently asked questions about for_each
What should you keep in mind with for_each?
Use each.key and each.value inside the block to access the current item. Maps work well when each item has several settings, such as one map entry per environment or per DNS record. The values must be known during planning, so you cannot loop over something that is only created during the same apply.
What does an example of for_each look like?
resource "aws_iam_user" "u" { for_each = toset(["alice", "bob"]) name = each.value } At a glance
| Category | Terraform |
|---|---|
| Explained by | Reinier de la Parra |
| Updated |