【问题标题】:how to print private IP from the module created using terraform-google-modules如何从使用 terraform-google-modules 创建的模块中打印私有 IP
【发布时间】:2021-02-23 03:29:15
【问题描述】:

我已经使用 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?

【问题讨论】:

  • 你的“comput_instance”模块是什么样子的?你必须定义例如输出 "private_ips" { value=... } 其中 value 分配了您的 google 实例的 private_ip。
  • 感谢 Fedor,就像 Vikram 所说的那样,模块本身没有导出,我无法获得输出。

标签: google-cloud-platform terraform-provider-gcp terraform-modules


【解决方案1】:

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

更好用,google_compute_instance_templategoogle_compute_instance_from_template的资源块

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

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

【讨论】:

  • 谢谢。这是我第一次使用模块。看起来最好自己编写所有内容,或者创建自己的模块,这样更灵活,我可以得到我想要的任何输出。
【解决方案2】:

模块输出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"
  },
]

【讨论】:

  • 谢谢Shabirmean。很有帮助
猜你喜欢
  • 2020-05-03
  • 2019-03-23
  • 1970-01-01
  • 2021-06-26
  • 2021-12-30
  • 2018-07-18
  • 2021-07-13
  • 1970-01-01
  • 2021-02-18
相关资源
最近更新 更多