Hi all,
I created a map and I need to filter one element of the map. This is my map:
interfaces = {
nic1 = {
name = "main"
ip = "xyz"
primary = true
},
nic2 = {
name = "admin"
ip = "zyx"
primary = false
}
}
I’d like to get only the element where primary = true
. I have tried the following:
primary_interface = [
for interface in keys(interfaces):
interfaces[interface]
if interfaces[interface].primary
]
This gives me the following error:
Error: Invalid reference
on main.tf line 12, in locals:
12: interfaces[interface]
A reference to a resource type must be followed by at least one attribute
access, specifying the resource name.
Thanks in advance for any advice you can offer.
Hi @suexec92,
If that interfaces
declaration is inside a locals
block then the correct way to refer to it elsewhere in the configuration is as local.interfaces
, not just interfaces
.
Currently Terraform thinks you are trying to refer to a resource of type interfaces
, because that’s the default handling of any top-level symbol that isn’t considered special by Terraform.
locals {
interfaces = {
nic1 = {
name = "main"
ip = "xyz"
primary = true
},
nic2 = {
name = "admin"
ip = "zyx"
primary = false
}
}
}
output "filter" {
value = { for k, v in local.interfaces : k => v if v.primary == true }
}
Something like that?
1 Like
Thank you! Prepending “local.” was the key!
Thought about it a bit more and this is probably more what you’re looking for, so you can use the filter to pick from the input array:
bent@DESKTOP-KEO4V17:/tmp/filtermap$ cat main.tf
locals {
interfaces = {
nic1 = {
name = "main"
ip = "10.0.0.1"
primary = true
},
nic2 = {
name = "admin"
ip = "127.0.0.1"
primary = false
}
}
filter = [ for k, v in local.interfaces : k if v.primary == true ]
primary = local.filter[0]
}
output "primary_ip" {
value = local.interfaces[local.primary].ip
}
bent@DESKTOP-KEO4V17:/tmp/filtermap$ terraform apply
Apply complete! Resources: 0 added, 0 changed, 0 destroyed.
Outputs:
primary_ip = 10.0.0.1
bent@DESKTOP-KEO4V17:/tmp/filtermap$
1 Like