@ -147,6 +147,59 @@ For example:
collections by
[using the `setproduct` function inside a `for` expression ](/docs/language/functions/setproduct.html#finding-combinations-for-for_each ).
### Chaining `for_each` Between Resources
Because a resource using `for_each` appears as a map of objects when used in
expressions elsewhere, you can directly use one resource as the `for_each`
of another in situations where there is a one-to-one relationship between
two sets of objects.
For example, in AWS an `aws_vpc` object is commonly associated with a number
of other objects that provide additional services to that VPC, such as an
"internet gateway". If you are declaring multiple VPC instances using `for_each`
then you can chain that `for_each` into another resource to declare an
internet gateway for each VPC:
```hcl
variable "vpcs" {
type = map(object({
cidr_block = string
}))
}
resource "aws_vpc" "example" {
# One VPC for each element of var.vpcs
for_each = var.vpcs
# each.value here is a value from var.vpcs
cidr_block = each.value.cidr_block
}
resource "aws_internet_gateway" "example" {
# One Internet Gateway per VPC
for_each = aws_vpc.example
# each.value here is a full aws_vpc object
vpc_id = each.value.id
}
output "vpc_ids" {
value = {
for k, v in aws_vpc.example : k => v.id
}
# The VPCs aren't fully functional until their
# internet gateways are running.
depends_on = [aws_internet_gateway.example]
}
```
This chaining pattern explicitly and concisely declares the relationship
between the internet gateway instances and the VPC instances, which tells
Terraform to expect the instance keys for both to always change together,
and typically also makes the configuration easier to understand for human
maintainers.
## Referring to Instances
When `for_each` is set, Terraform distinguishes between the block itself