Terraform Multi Level Maps

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}"
  }
}

Hi @Eva,

You didn’t mention which problems you ran into here, so perhaps there’s more to this than I’m seeing on my first read, but the first thing I noticed here is that the value you’ve given for instance_config doesn’t match the type constraint you specified: you’ve written either a map of maps of string or a map of objects, but the type constraint for a list of maps of string.

Based on what you wrote later on I assume you intended the map of objects interpretation, in which case this would be a suitable type constraint for that:

variable "instance_config" {
  type    = map(object({
    instance_name  = string
    instance_image = string
    instance_type  = string
  }))
  default = {}
}

That should at least make the value you have in the .tfvars file be accepted by the type constraint. I’m not sure what your intent was for the resource configuration you showed here – it doesn’t seem to be valid syntax – but hopefully at least the above will get you past the first problem and then we can talk some more about your intended outcome for this resource "google_compute_instance" "vm_instance" block.

3 Likes

@apparentlymart thanks that helped me resolve my issue