If I try a setproduct function I have (for a for_each in another resource)
The given “for_each” argument value is unsuitable: the “for_each” argument
must be a map, or set of strings, and you have provided a value of type list
of tuple.
The example you gave of your intended result shows four map elements, but only two unique keys. A map is a data structure where each element is identified by a unique string, so a map exactly like you showed isn’t possible, but maybe you meant a map of lists instead, like this?
If so, I think something like this would get that result:
locals {
subnet_ranges = {
for pair in setproduct(var.A, var.B) : pair[0] => pair[1]...
}
}
The above uses a less-common feature of for expressions: the ... after the value expression activates grouping mode, where each unique key maps to a list of all of the values corresponding to that key.
If I misunderstood what you’re trying to do, it would be helpful if you could share a little more about the underlying problem you are trying to solve – that is, your current goal rather than your current idea for how to meet that goal – and then I might be able to offer some broader suggestions on how to get that done with different Terraform language features.
So I can do a clean for_each and use each.value.subnet to retreive value
But I don’t know how to build this kind of map using my 2 list(tring) variables ?
Hi @opsrom! I’m glad you found a working solution. Here’s an adaptation of your most recent example to use for_each instead, by constructing a map from your list:
resource "random_pet" "test" {
for_each = {
for r in local.routes : "${r.subnet}-${r.cidr}" => r
}
prefix = format("%s-%s", each.value.subnet, each.value.cidr)
length = 5
}
The for expression in the for_each argument projects your list into a map with generated keys like subnetID1-xx.xx.xx.xx/16, which contain all of the values from the object and will thus be unique across all values in the local.routes list.
Terraform will then track these with addresses based on those keys: