创建 GCP 多个 VM - 输出 IP 地址

Create GCP Multiple VM's - Output IP address

在 Azure Terraform 代码中,我正在打印多个 IP 地址的输出

output "all_slave_private_ips" {
value = "${join(",", azurerm_network_interface.jmeter_slave_nic.*.private_ip_address)}"
}

在 GCP Terraform 代码中,可以告诉我输出多个 IP 地址的语法吗?

output "slave_private_ips" {
  value = "${join(",", slice(google_compute_instance.jmeter_slave[*].network_interface.[*].network_ip, 0, var.JMETER_SLAVE_COUNT))}"
}

如果您有多个 VM,这里是您可以使用的输出,其中使用了实例计数和 count.index

output "ip" {
  value = "${google_compute_instance.default[*].network_interface.0.access_config.0.nat_ip}"
}

main.tf 文件

resource "google_compute_instance" "default" {
  name         = "virtual-machine-from-terraform-${count.index}"
  machine_type = "e2-micro"
  zone         = "us-central1-a"
  count        = 2
  boot_disk {
    initialize_params {
      image = "debian-cloud/debian-9"
    }
  }

  network_interface {
    network = "default"

    access_config {
      // Include this section to give the VM an external ip address
    }
  }

    metadata_startup_script = "sudo apt-get update && sudo apt-get install apache2 -y && echo '<!doctype html><html><body><h1>Hello World!${count.index}</h1></body></html>' | sudo tee /var/www/html/index.html"

    // Apply the firewall rule to allow external IPs to access this instance
    tags = [element(var.instance_tag,count.index)]
}

variable "instance_tag" {
  type = list
  default = ["http-one", "http-two"]
}

resource "google_compute_firewall" "http-server" {
  name    = "default-allow-http-terraform"
  network = "default"

  allow {
    protocol = "tcp"
    ports    = ["80"]
  }

  // Allow traffic from everywhere to instances with an http-server tag
  source_ranges = ["0.0.0.0/0"]
  target_tags   = ["http-server"]
}
output "ip" {
  value = "${google_compute_instance.default[*].network_interface.0.access_config.0.nat_ip}"
}