Terraform Multi Level Maps

Viewed 273

I'm getting errors on "terraform plan" when trying to use a multi-level map. I am unable to use the map in google_compute_instance module. My goal is to launch multiple VM's with different properties using a single google_compute_instance module. I request you to help me correct my main.tf or suggest me to achieve my goal

Variable.tf

variable "instance_config" {
  type    = list(map(string))
  default = []
}

.tfvars

instance_config = {
  test-vm1 = {
      instance_name  = "test-vm1"
      instance_image = "debian-cloud/debian-8"
      instance_type =  "n1-standard-4"
     },

  test-vm2 = {
      instance_name  = "test-vm2"
      instance_image = "debian-cloud/debian-9"
      instance_type =  "f1-micro"
     }
}

main.tf

resource "google_compute_instance" "vm_instance" {

 { for instance_name, instance_type, instance_image in var.instance_config :
  name         = instance_config.instance_name
  machine_type = instance_config.instance_type
  tags         = var.instance_tags
  boot_disk {
    initialize_params {
      image =  instance_config.instance_image
    }
  }
 }

  network_interface {
    network = "${var.gcp_network}"
  }
}
1 Answers

Your syntax for for_each is incorrect and your instance_config has wrong format. It should be:

variable "instance_config" {

  type = map(object({
        instance_name  = string
        instance_image = string
        instance_type  = string
       }))
  
  default = {
    test-vm1 = {
        instance_name  = "test-vm1"
        instance_image = "debian-cloud/debian-8"
        instance_type =  "n1-standard-4"
       },

    test-vm2 = {
        instance_name  = "test-vm2"
        instance_image = "debian-cloud/debian-9"
        instance_type =  "f1-micro"
       }
  }
}

resource "google_compute_instance" "vm_instance" {

  for_each     = var.instance_config
   
  name         = each.value.instance_name
  machine_type = each.value.instance_type
  tags         = var.instance_tags

  boot_disk {
    initialize_params {
      image = each.value.instance_image
    }
  }

  network_interface {
    network = var.gcp_network
  }
}
Related