for_each
The for_each argument, which creates one instance of a resource or module per element of a map or set, addressed by key such as name["a"].
In more detail
Because each instance is identified by its key rather than its position, adding or removing one element leaves the others untouched. Keys must be known at plan time, so they cannot come from attributes that are only known after apply. Inside the block, each.key and each.value give the current element.
Example
resource "null_resource" "subnet" {
for_each = var.subnets
triggers = { name = each.value }
}Related terms
- count meta-argument — The count argument, which creates that many numbered copies of a resource or module, addressed as name[0], name[1] and so on.
- resource instance — One of the objects a resource block produces; a block with count or for_each has several, each with its own index or key.
- type constraint — The type argument of a variable, such as string, number, bool, list(string), map(string) or object({...}), which rejects values of the wrong shape.
- meta-argument — An argument Terraform itself understands on any resource or module block, such as count, for_each, depends_on, provider and lifecycle.
Taught in
- Writing A Custom Network Module — Infrastructure as Code with Terraform
- Scaling Resources With Count — Infrastructure as Code with Terraform
- Iterating Over Maps With For Each — Infrastructure as Code with Terraform
- One Hour, No Weights Published — HashiCorp Terraform Associate (004) Exam Prep
- Infrastructure As Code, And One Workflow For Every Platform — HashiCorp Terraform Associate (004) Exam Prep
- Providers: How Terraform Reaches Every API — HashiCorp Terraform Associate (004) Exam Prep
- Versions, The Lock File And Provider Aliases — HashiCorp Terraform Associate (004) Exam Prep
- State: Terraform's Memory Of What It Built — HashiCorp Terraform Associate (004) Exam Prep
- Resources, Data Sources And The References Between Them — HashiCorp Terraform Associate (004) Exam Prep
- Complex Types: Lists, Sets, Maps, Objects And Tuples — HashiCorp Terraform Associate (004) Exam Prep
- Expressions And Functions: Making Configuration Compute — HashiCorp Terraform Associate (004) Exam Prep