'Terraform Variable looping to generate properties

I have to admit, this is the first time I have to ask something that I dont even myself know how to ask for it or explain, so here is my code. It worth explains that, for specific reasons I CANNOT change the output resource, this, the metadata sent to the resource has to stay as is, otherwise it will cause a recreate and I dont want that.

currently I have a terraform code that uses static/fixed variables like this

user1_name="Ed"
user1_Age ="10"
user2_name="Mat"
user2_Age ="20"

and then those hard typed variables get used in several places, but most importanly they are passed as metadata to instances, like so

resource "google_compute_instance_template" "mytemplate" {
  ...
  metadata = {
    othervalues     = var.other     
    user1_name      = var.user1_name
    user1_Age       = var.user1_Age
    user2_name      = var.user2_name
    user2_Age       = var.user2_Age
  }
  ...
}

I am not an expert on terraform, thus asking, but I know for fact this is 100% ugly and wrong, and I need to use lists or array or whatever, so I am changing my declarations to this:

users = [
  { "name" : "yo", "age" : "10",  "last" : "other" },
  { "name" : "El", "age" : "20",  "last" : "other" }
]

but then, how do i get around to generate the same result for that resource? The resulting resource has to still have the same metadata as shown. Assuming of course that the order of the users will be used as the "index" of the value, first one gets user1_name and so on...

I assume I need to use a for_each loop in there but cant figure out how to get around a loop inside properties of a resource

Not sure if I make myself clear on this, probably not, but didn't found a better way to explain.



Solution 1:[1]

metadata is not a block, but a regular attribute of type map. So you can do:


# it would be better to use map, not list for users:
variable "users"
  default {
   user1 =  { "name" : "yo", "age" : "10",  "last" : "other" },
   user2 =  { "name" : "El", "age" : "20",  "last" : "other" }
   }
}

resource "google_compute_instance_template" "mytemplate" {
  
  for_each = var.users

  metadata = each.value
  #...
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Marcin