I am trying to access all the values from a for_each statement in google_compute_instance
resource
I want to get all the values [dev-1, dev-2]
in thename
attribute and parse it to vm_name
in my metadata_startup_script
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"
})
}
I am unable to get all compute instance from the name
argument
I get this error message
╷
│ Error: Cycle: google_compute_instance.compute_instance["2"], google_compute_instance.compute_instance["1"]
│
│
How do I resolve this issue so I can get all the virtual machine name and parse it to vm_name
variable?
CodePudding user response:
I would change the hardcoded elements in your for_each
to a variable,
and pass that to your vm_name, something like this:
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"
})
}