Reputation: 35
I'd appreciate some help in better understanding when to use each.key vs each.value.
I have a transit gateway and wanted to ensure that any new transit gateway attachment is propagated into all available route tables. My code looked like this:
locals {
propagation_rt_ids = {
tgw-rt-001 = "tgw-rtb-xxx”
tgw-rt-002 = "tgw-rtb-yyy"
tgw-rt-003 = "tgw-rtb-zzz”
}
}
resource "aws_ec2_transit_gateway_route_table_propagation" "propagate_attachment” {
for_each = local.propagation_rt_ids
transit_gateway_attachment_id = data.aws_ec2_transit_gateway_vpc_attachment.tenant_id.id
transit_gateway_route_table_id = local.propagation_rt_ids[each.value]
}
When I referenced each.value and ran terraform plan, I got errors saying: The given key does not identify an element in this collection value
I eventually found a similar example where [each.key] was used. I tried [each.key] and it worked.
What I am trying to understand is this: I was thinking that the “transit_gateway_route_table_id” argument under aws_ec2_transit_gateway_route_table_propagation is expecting a route table ID as its value. So I assumed the correct thing to specify there was local.propagation_rt_ids[each.value] which should retrieve each of the route-table IDs in the key/value pair. Why is [each.value] not valid in this scenario?
Upvotes: 1
Views: 2475
Reputation: 18148
Maps and objects in terraform are represented by key/value pairs. From the documentation [1]:
{
name = "John"
age = 52
}
Map attributes can be accessed by using either the dot notation, e.g., local.propagation_rt_ids.tgw-rt-001
or using a square-bracket index notation local.propagation_rt_ids["tgw-rt-001"]
. So, for maps, in order to get a value of an attribute, you have to reference a certain key. If we take the example you posted and use terraform console
:
> local.propagation_rt_ids
{
"tgw-rt-001" = "tgw-rtb-xxx" # key = value
"tgw-rt-002" = "tgw-rtb-yyy" # key = value
"tgw-rt-003" = "tgw-rtb-zzz" # key = value
}
> local.propagation_rt_ids.tgw-rt-001
"tgw-rtb-xxx"
> local.propagation_rt_ids["tgw-rt-001"]
"tgw-rtb-xxx"
Now, if I were to try and reference a value instead of a key:
> local.propagation_rt_ids["tgw-rtb-xxx"]
╷
│ Error: Invalid index
│
│ on <console-input> line 1:
│ (source code not available)
│
│ The given key does not identify an element in this collection value.
╵
The first example works, because the attribute value is being fetched by using one of the keys, i.e. "tgw-rt-001"
. In the second example, the error is the same as the one you got, because I tried to get an attribute value based on a key that does not exist, as it is in fact a value. In other words, a key references a value but a value references nothing, so something like:
key1 -> value1 -> no reference
key2 -> value2 -> no reference
key3 -> value3 -> no reference
[1] https://developer.hashicorp.com/terraform/language/expressions/types#maps-objects
Upvotes: 3