Search code examples
dynamicterraformoracle-cloud-infrastructure

How can we dynamically generate a list of map in terraform?


I have a list of rules which i want to generate at runtime as it depends on availability_domains where availability_domains is a list

availability_domains = [XX,YY,ZZ]

locals {
  rules = [{
    ad = XX
    name = "service-XX",
    hostclass = "hostClassName",
    instance_shape = "VM.Standard2.1"
...
  },{
    ad = YY
    name = "service-YY",
    hostclass = "hostClassName",
    instance_shape = "VM.Standard2.1"
...
  }, ...]
}

Here, all the values apart from ad and name are constant. And I need rule for each availability_domains.

I read about null_resource where triggers can be used to generate this but i don't want to use a hack here.

Is there any other way to generate this list of map?

Thanks for help.


Solution

  • First, you need to fix the availability_domains list to be a list of strings.

    availability_domains = ["XX","YY","ZZ"]
    

    Assuming availability_domains is a local you just run a forloop on it.

    locals {
    availability_domains = ["XX","YY","ZZ"]
    all_rules = {"rules" = [for  val in local.availability_domains :  { "ad" : val, "name" : "service-${val}" ,  "hostclass" : "hostClassName", "instance_shape" : "VM.Standard2.1"}] }
    }
    

    or if you dont want the top level name to the array then this should work as well

        locals {
    availability_domains = ["XX","YY","ZZ"]
    rules = [for  val in local.availability_domains :  { "ad" : val, "name" : "service-${val}" ,  "hostclass" : "hostClassName", "instance_shape" : "VM.Standard2.1"}] 
    }