如何从使用 terraform-google-modules 创建的模块打印私有 IP

how to print private IP from the module created using terraform-google-modules

我已经使用 terraform 模块创建了一些 gcp 实例:

module "instance_template" {
  source = "terraform-google modules/vm/google//modules/instance_template"
...
}
module "compute_instance" {
  source             = "terraform-google- 
   modules/vm/google//modules/compute_instance"
  num_instances      = 4
  ...
}

那我运行 terraform应用后如何获取并输出这4个实例的私有ip?

此模块没有作为私有 Ips 的输出。它只有输出 instances_self_links 和 available_zones

更好用,google_compute_instance_templategoogle_compute_instance_from_template

的资源块

然后你可以使用输出块来获取所有 4 个私有 ips

output {
value = google_compute_instance_from_template.instances[*].network_ip
}

模块输出 instances_details,您可以从中获取 ip 地址。

下面是获取所有创建的实例的IP的例子

output "vm-ips" {
  value = flatten(module.compute_instance[*].instances_details.*.network_interface.0.network_ip)
}

输出:

vm-ips = [
  "10.128.0.14",
  "10.128.0.15",
  "10.128.0.16",
]

在您使用 for-each 重复模块以创建具有不同参数的实例组。

  • 说 2 个实例,每个实例的主机名都以 2 个组中的某个前缀开头

然后,你可以得到他们所有的IP如下:

output "vm-ips" {
  value = flatten([
     for group in module.compute_instance[*] : [
      for vm_details in group: [
        for detail in vm_details.instances_details: {
          "name" = detail.name
          "ip" = detail.network_interface.0.network_ip
        }
      ]
     ]
  ])
}

输出:

vm-ips = [
  {
    "ip" = "10.128.0.17"
    "name" = "w1-001"
  },
  {
    "ip" = "10.128.0.18"
    "name" = "w1-002"
  },
  {
    "ip" = "10.128.0.20"
    "name" = "w2-001"
  },
  {
    "ip" = "10.128.0.19"
    "name" = "w2-002"
  },
]