for_each
for_each is a meta-argument that makes copies keyed by name instead of by number. It takes a map or a set, and each copy keeps its own key.
One copy per key
Each map entry becomes one file. each.key names the file and each.value fills it.
variable "files" {
type = map(string)
default = {
alpha = "First file."
beta = "Second file."
}
}
resource "local_file" "note" {
for_each = var.files
content = each.value
filename = "${path.module}/${each.key}.txt"
}A list becomes a set
toset turns a list into a set of strings. The set then works as the keys for for_each.
variable "names" {
type = list(string)
default = ["alpha", "beta"]
}
resource "local_file" "note" {
for_each = toset(var.names)
content = "File ${each.key}."
filename = "${path.module}/${each.key}.txt"
}Read one copy by key
A copy is read by its key in square brackets. The key never changes when other keys are added.
output "beta" {
value = local_file.note["beta"].filename
}Example
variable "files" {
type = map(string)
default = {
alpha = "First file."
beta = "Second file."
gamma = "Third file."
}
}
resource "local_file" "note" {
for_each = var.files
content = each.value
filename = "${path.module}/${each.key}.txt"
}
output "names" {
value = [for f in local_file.note : f.filename]
}Key points
- for_each takes a map or a set of strings.
- Each copy is named by its key, not by a number.
- Inside the block, each.key is the key and each.value is the value.
- Removing one key removes only that copy.
- The other copies are untouched.
- A list must be turned into a set or a map before for_each can use it.
for_each makes one copy per map entry. each.key is the name and each.value is the text, so removing beta leaves alpha and gamma untouched.
Note
A map keeps its keys in a stable order, so copies do not shift.
Try it Yourself
Edit the code, then press Run.
Running is simulated · Rust Playground
Exercise
What happens when you remove one key from a for_each map?