0

Hi I am trying fetch the name and the public IP address of the the compute instances created by google_compute_instance_template using terraform, but I am getting an empty list at the first time read after the first terraform apply. Please note that it works fine on the second terraform apply.

main.tf:

resource "google_compute_region_instance_group_manager" "instance_group_manager" {
  region = var.region
  name = "${var.prefix}-igm-${random_string.random_string.result}"
  wait_for_instances = true
  version {
    instance_template = google_compute_instance_template.instance_template.id
    name = "${var.prefix}-tmplt"
  }
  base_instance_name = "${var.prefix}-${random_string.random_string.result}"
}

output.tf:

#Get the list of instances
data "google_compute_region_instance_group" "mig_data" {
    name = google_compute_region_instance_group_manager.instance_group_manager.name
    region = var.region
}

#Get each instance data 
data "google_compute_instance" "intance_data" {
  count = var.instances_min_grop_size
  self_link = data.google_compute_region_instance_group.mig_data.instances[count.index].instance
}

#Print the data needed
output "public_ips" {
  value = [
    for instance in data.google_compute_instance.intance_data: 
    [
      instance.name, instance.network_interface.0.access_config.0.nat_ip
    ]
  ]
}

first run output:

Error: Invalid index
│
│   on output.tf line 49, in data "google_compute_instance" "intance_data":
│   49:   self_link = data.google_compute_region_instance_group.mig_data.instances[count.index].instance
│     ├────────────────
│     │ count.index is 0
│     │ data.google_compute_region_instance_group.mig_data.instances is empty list of object
│
│ The given key does not identify an element in this collection value: the collection has no elements.
╵
╷
│ Error: Invalid index
│
│   on output.tf line 49, in data "google_compute_instance" "intance_data":
│   49:   self_link = data.google_compute_region_instance_group.mig_data.instances[count.index].instance
│     ├────────────────
│     │ count.index is 1
│     │ data.google_compute_region_instance_group.mig_data.instances is empty list of object
│

Second run output:

public_ips = [
  [
    "chkp-tf-mig-07m81-97nz",
    "35.231.4.112",
  ],
  [
    "chkp-tf-mig-07m81-bkj2",
    "34.23.235.90",
  ],
]
Grzenio
  • 35,875
  • 47
  • 158
  • 240

0 Answers0