Jeff
Jeff Cloud Systems Architect
1 min read

Terraform Loop Through Nested Map

Terraform Loop Through Nested Map

How to use a nested map variable in a loop to create Terraform resources

Requires Terraform >v0.12

Create a Map Variable

Open or create the variables.tf (this can also be done as a local) and add the following

variable virtual_machines = {
  default = {
    "vm01" = {
      "region" = "eastus"
      "disk_size" = "200"
      "username" = "myadmin"
    },
    "vm02" = {
      "region" = "eastus"
      "disk_size" = "200"
      "username" = "myadmin"
    }
  }
}

Loop Through Map Variable

This is not real Terraform code, you will need to plug these values into your provider

resource "provider" "vm" {
  count     = length(var.virtual_machines)
  name      = element(keys(var.virtual_machines), count.index)
  region    = var.virtual_machines[element(keys(var.virtual_machines), count.index)]["vm_size"]
  disk_size = var.virtual_machines[element(keys(var.virtual_machines), count.index)]["disk_size"]
  username  = var.virtual_machines[element(keys(var.virtual_machines), count.index)]["username"]
}