The for_each expression allows you to loop over lists, sets, and maps to create (a) multiple copies of an entire resource, (b) multiple copies of an inline block within a resource, or (c) multiple copies of a module. Let’s first walk through how to use for_each to create multiple copies of a resource.
The syntax looks like this:
resource "
for_each =
[CONFIG ...]
}
where COLLECTION is a set or map to loop over (lists are not supported when using for_each on a resource) and CONFIG consists of one or more arguments that are specific to that resource. Within CONFIG, you can use each.key and each.value to access the key and value of the current item in COLLECTION.
For example, here’s how you can create the same three IAM users using for_each on a resource:
resource "aws_iam_user" "example" {
for_each = toset(var.user_names)
name = each.value
}
Note the use of toset to convert the var.user_names list into a set. This is because for_each supports sets and maps only when used on a resource. When for_each loops over this set, it makes each username available in each.value. The username will also be available in each.key, though you typically use each.key only with maps of key-value pairs.
Once you’ve used for_each on a resource, it becomes a map of resources, rather than just one resource (or an array of resources as with count). To see what that means, remove the original all_arns and first_arn output variables, and add a new all_users output variable:
output "all_users" {
value = aws_iam_user.example
}