foreachterraformterraform-provider-azurelocal-variablesmaplist

Iterate through multiple lists using locals in Terraform code


I have the following list of Resource Group names and Virtual Machine Names, I will like to create a map using locals so I can iterate through it using each.key and each.value in my code.

VARIABLES:

 variable "vm_names" {
    default = [
    "vm1",
    "vm2",
    "vm3",
    "vm4",
    "vm5"
    ]

 variable "rg_names" {
    default = [
    "rg1",
    "rg2",
    "rg3",
    "rg4",
    "rg5"
]     

LOCALS:

locals {
  vm = var.vm_names
  rg = var.rg_names
  vmrg=[for k,v in zipmap(local.vm, local.rg):{
    vm = k
    rg = v
  }]
}

RESULT:

 + vmrg = [
      + {
          + rg = "rg1"
          + vm = "vm1"
        },
      + {
          + rg = "rg2"
          + vm = "vm2"
        },
      + {
          + rg = "rg3"
          + vm = "vm3"
        },
      + {
          + rg = "rg4"
          + vm = "vm4"
        },
      + {
          + rg = "rg5"
          + vm = "vm5"
        },
    ]

DESIRED RESULT:

vmrg = {
            vm1 = "rg1"
            vm2 = "rg2"
            vm3 = "rg3"
            vm4 = "rg4"
            vm5 = "rg5"
            }

Solution

  • Actually, it is much simpler and you were already close to figuring it out. The only thing you need is the zipmap built-in function:

    vmrg = zipmap(local.vm, local.rg)
    

    will yield:

    > local.vmrg
    {
      "vm1" = "rg1"
      "vm2" = "rg2"
      "vm3" = "rg3"
      "vm4" = "rg4"
      "vm5" = "rg5"
    }