简体   繁体   中英

Terraform - How can I reference a resource containing a "for_each" argument to another resource?

I created a resource that produces a list of VM's using for_each argument. I'm having trouble trying to reference this resource to my web_private_group .

resource "google_compute_instance_group" "web_private_group" {
  name = "${format("%s","${var.gcp_resource_name}-${var.gcp_env}-vm-group")}"
  description = "Web servers instance group"
  zone = var.gcp_zone_1
  network = google_compute_network.vpc.self_link

  # I've added some attempts I've tried that do not work...
  instances = [
    //google_compute_instance.compute_engines.self_link
    //[for o in google_compute_instance.compute_engines : o.self_link]
    {for k, o in google_compute_instance.compute_engines : k => o.self_link}
    //google_compute_instance.web_private_2.self_link
  ]
    named_port {
    name = "http"
    port = "80"
  }
    named_port {
    name = "https"
    port = "443"
  }
}


# Create Google Cloud VMs 
resource "google_compute_instance" "compute_engines" {
  for_each = var.vm_instances
  name = "${format("%s","${var.gcp_resource_name}-${var.gcp_env}-each.value")}"
  machine_type = "e2-micro"
  zone         = var.gcp_zone_1
  tags         = ["ssh","http"]

  boot_disk {
    initialize_params {
      image = "debian-10"
    }
  }
}

variable "vm_instances" {
  description = "list of VM's"
  type        = set(string)
  default     = ["vm1", "vm2", "vm3"]
} 

How can I properly link my compute_engines to my web_private_group resource within the instances= [] block?

Edit: To further clarify, how can I state the fact that there are multiple instances within my compute_engines resource?

You probably just need to use a splat expression as follows:

instances = values(google_compute_instance.compute_engines)[*].id

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM