Terraform for_each,计数索引

Terraform for_each, Count Index

我正在尝试从 google_compute_instance 资源

中的 for_each 语句访问所有值

我想获取name属性中的所有values [dev-1, dev-2]并在我的metadata_startup_script

中将其解析为vm_name
resource "google_compute_instance" "compute_instance" {
  project  = var.project_id
  for_each = toset(["1", "2"])
  name     = "dev-${each.key}"
  machine_type = "e2-micro"
  zone         = "${var.region}-b"

  boot_disk {
    initialize_params {
      image = "ubuntu-os-cloud/ubuntu-1804-lts"
    }
  }

  network_interface {
    network = "default"
    access_config {
    }
  }

  lifecycle {
    ignore_changes = [attached_disk]
  }
  
  metadata_startup_script = templatefile("copy.tftpl", {
    vm_name         = "${google_compute_instance.compute_instance.0.name}"
    nfs_ip          = "${google_filestore_instance.instance.networks[0].ip_addresses[0]}"
    file_share_name = "${google_filestore_instance.instance.file_shares[0].name}"
    zone            = "${var.region}-b"
  })
}

我无法从 name 参数中获取所有计算实例

我收到此错误消息

╷
│ Error: Cycle: google_compute_instance.compute_instance["2"], google_compute_instance.compute_instance["1"]
│ 
│ 

如何解决这个问题,以便获取所有虚拟机名称并将其解析为 vm_name 变量?

我会将您 for_each 中的硬编码元素更改为变量,
并将其传递给您的 vm_name,如下所示:

locals {
  compute_names = ["dev-1", "dev-2"]
}

resource "google_compute_instance" "compute_instance" {
  project      = var.project_id
  for_each     = toset(local.compute_names)
  name         = each.key
  machine_type = "e2-micro"
  zone         = "${var.region}-b"

...
  
  metadata_startup_script = templatefile("copy.tftpl", {
    vm_name         = local.compute_names
...
    zone            = "${var.region}-b"
  })
}