DELAPARRA
Index
Color
NL
Category: Terraform

for_each

Explained by Updated

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.

Definition source Coders Lingo, CC BY 4.0

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

CategoryTerraform
Explained by
Updated

More Terraform terms

All terms starting with F

Skills

Download all skills (zip)

Manuals

Related services

Need any help?

Stuck on one of these in your own project? Tell me what you are working on and I will tell you how I would approach it.