Hi,
If you have a list(object), containing let’s say the following data:
demo_list_object = [
{
"Key1" = "Value1"
"Key2" = "Value2"
"Key3" = "Value3"
"Key4" = "Value4"
},
{
"Key1" = "Value1"
"Key2" = "Value2"
"Key3" = "ValueX"
"Key4" = "Value4"
},
{
"Key1" = "Value1"
"Key2" = "Value2"
"Key3" = "ValueY"
"Key4" = "Value4"
}
]
In this object, all of the single values could potentially be the same, but not all of them at the same time. So in others words, to be able to uniquely identify each of the objects, it has to be done by combining all of the key values to get something unique.
I need this unique value to be able to key up the resources in a for_each, so that it wont complain similarly to this:
Two different items produced the key “XXX” in this ‘for’ expression. If
duplicates are expected, use the ellipsis (…) after the value expression to
enable grouping by key.
Inside the same for_each, i’d also like to use a randomly generated string to name resources.
To achieve this right now, I’m doing the following (which for me looks quite ugly):
resource "random_string" "random" {
for_each = { for demolistobject in var.demo_list_object : "${demolistobject.Key1} ${demolistobject.Key2} ${demolistobject.Key3} ${demolistobject.Key4}" => demolistobject }
special = false
number = true
length = 6
}
resource "azurerm_virtual_machine" "main" {
for_each = { for demolistobject in var.demo_list_object : "${demolistobject.Key1} ${demolistobject.Key2} ${demolistobject.Key3} ${demolistobject.Key4}" => merge(demolistobject, {
resources_name_affix = "${random_string.random["${demolistobject.Key1} ${demolistobject.Key2} ${demolistobject.Key3} ${demolistobject.Key4}"].result}"
})
}
name = "VM-${each.value.resources_name_affix}"
...
}
This enbles me to couple a random generated string, from the random_string loop created resources, with the azurerm_virtual_machine loop created resources. Hence coupling each of the single randomly generated strings, to a specific virtual machine. This takes care of the key of the resources being unique, as well as the acutal virtual machine scale set name being unique as well. But I wonder, is there any nicer way to do this? Am I going at this in the wrong way? Is there something that could be improved in the code?
You can’t in any way have the same for_each for two resources, right?
Something like this I mean:
for_each {
resource "random_string" "random" {
special = false
number = true
length = 6
}
resource "azurerm_virtual_machine" "main" {
name = "VM-${each.value.random_string.random.result}"
...
}
}
I appreciate all input, I want to go at this in the best way possible!
Thank you!