I am trying to get the networks nic element values using the for_each loop, below is the sample terraform code I am trying with,
locals {
image = {
nodes ={
vm1 ={
name = "vm1"
networks ={
nic1 = {
name = "vm1-nic1"
}
nic2 ={
name ="vm1-nic2"
}
}
},
vm2 ={
name = "vm2"
networks ={
nic1 = {
name = "vm2-nic1"
}
nic2 ={
name = "vm2-nic2"
}
}
}
}
}
}
output "iterate" {
value = [
for_each = local.image.nodes[].networks
]
}
Output error while terraform plan.
terraform plan
╷
│ Error: Missing item separator
│
│ on provider.tf line 111, in output "iterate":
│ 110: value = [
│ 111: for_each = local.image.nodes.nodes
│
│ Expected a comma to mark the beginning of the next item.
can someone throw some light on the fix ? Thank You in advance.
The error suggests that a syntax issue on the line
for_each = local.image.nodes.nodes
. This is not the correct way to iterate over elements in Terraform.The main issue in the configuration you shared is incorrect use of
for_each
in the output block**: In Terraform,for_each
is used with resources and modules, not within an output block directly. To iterate over a map or a list in an output, you use a list comprehension orfor
loop.I rewrite the configuration which will use a
for
loop inside the output block to iterate over each node and its network interfaces.My terraform configuation:
Output: