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

相关内容

  • 没有找到相关文章

最新更新