Updated on 2023-08-11 GMT+08:00

for_each

The function of for_each is similar to that of count. for_each uses key-value pairs or string sets to quickly fill values in corresponding attributes. This optimizes the script structure and helps understand the relationship between multiple instances.

When using the mapping type expression, you can use each.key and each.value to access the key and value of the mapping. For example, to create a VPC, you can use the key-value pair in for_each to flexibly configure the VPC name and CIDR.

  for_each = {
    vpc_demo1 = "192.168.0.0/16"
    vpc_demo2 = "172.16.0.0/16"
}

  name = each.key
  cidr = each.value
}

When a string set is used, each.key is equivalent to each.value and generally each.key is used. In addition, you can use the toset() function to convert the defined list type.

  for_each = toset(["secgroup_demo1", "secgroup_demo2"])
  name     = each.key
}

# Use variables to indicate for _each.
variable "secgroup_name" {
  type = set(string)
}
  for_each = var.secgroup_name
  name     = each.key
}

A key is required to access a resource created using for_each. The format is <Resource type>.<Name>[Key].

# Access vpc_demo1.
# ID for accessing vpc_demo1

Both count and for_each can be used to create multiple resources. You are advised to select either of them based on the following rules:

1. If the arguments of a resource instance are completely or mostly the same, you are advised to use count.

2. If some arguments of a resource need to use distinct values that cannot be directly derived from an integer, for_each is recommended.