I am trying to access a list inside a list of maps in terraform. The structure is as below:
dynamic.tfvars
--------------
nacl=[
{
"vpc_name" = "vpc1"
"acl_name" = "acl1"
"subnet_name" = ["sub1-az1","sub2-az2"]
},
{
"vpc_name" = "vpc2"
"acl_name" = "acl2"
"subnet_name" = ["sub1-az1","sub2-az2"]
}
]
I am trying to get "subnet_name"(a list) from the list of maps in my child module and it does not work. Below is the piece of code that i am using.
main.tf
-------
data "aws_vpc" "vpc_nacl" {
count = length(var.nacl[*])
filter {
name = "tag:Name"
values = [element(var.nacl[*]["vpc_name"],count.index)]
}
}
locals {
lcl_vpc_nacl = data.aws_vpc.vpc_nacl.*.id
}
data "aws_subnet_ids" "example" {
count = length(var.nacl[*]["subnet_name"])
vpc_id = element(local.lcl_vpc_nacl,count.index)
filter {
name = "tag:Name"
values = [element(var.nacl[*]["subnet_name"],count.index)]
}
}
I am getting the below error when terraform plan is executed.
│ Error: Incorrect attribute value type
│
│ on Modules\NACL\Main.tf line 28, in data "aws_subnet_ids" "example":
│ 28: values = [element(var.nacl[*]["subnet_name"],count.index)]
│ ├────────────────
│ │ count.index is 1
│ │ var.nacl is list of object with 5 elements
│
│ Inappropriate value for attribute "values": element 0: string required.
Any fixes or suggestions would be highly appreciated. Thanks in advance.
CodePudding user response:
From aws_subnet_ids data source documentation, I see values
within filter
expects a set.
Looking code you are almost there, but you are passing a list of lists to values
which is why you have this error.
element((var.nacl[*]["subnet_name"]), count.index)
extracts list of subnets in the format of list.
All you need is to convert into set and pass without square braces like below..
main.tf
-------
data "aws_subnet_ids" "example" {
count = length(var.nacl[*]["subnet_name"])
vpc_id = element(local.lcl_vpc_nacl,count.index)
filter {
name = "tag:Name"
values = toset(element((var.nacl[*]["subnet_name"]), count.index))
}
}
Give a try & let me know if this helps..