1

我使用 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 apply 后如何获取和输出这 4 个实例的私有 ip?

4

2 回答 2

2

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

更好用,资源块google_compute_instance_templategoogle_compute_instance_from_template

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

output {
value = google_compute_instance_from_template.instances[*].network_ip
}
于 2020-11-11T13:26:19.330 回答
1

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"
  },
]
于 2021-03-07T11:56:03.717 回答