【问题标题】:Terraform: get outputs with modules and for_eachTerraform:使用模块和 for_each 获取输出
【发布时间】:2021-03-31 14:33:35
【问题描述】:

我正在使用以下版本的 terraform:

root@sflowc01:~/terraform_proj# terraform version
Terraform v0.14.2
+ provider registry.terraform.io/dmacvicar/libvirt v0.6.2
+ provider registry.terraform.io/hashicorp/template v2.2.0

在我的模块 (./modules/singlevm/main.tf) 中,我将输出定义为:

output "ips" {
  value = libvirt_domain.db1.network_interface.0.addresses
}

当我在独立模式下运行这个模块时,我得到一个列表的输出,如下所示:(这是预期的)

ips = tolist([
  "192.168.122.167",
])

我的 tfvars 定义为:

myvms = {
  vm1 = {
    hostname  = "centos01"
    osdisk_gb = 20
    CPU_Count = 4
    RAM       = 256
    Image     = "CentOS-7-x86_64-GenericCloud.qcow2"
  }
  vm2 = {
    hostname  = "ubuntu01"
    osdisk_gb = 40
    CPU_Count = 8
    RAM       = 512
    Image     = "ubuntu-16.04-server-cloudimg-amd64-disk1.img"

  }
}

在我的根模块中,我正在使用 for_each 创建多个 VM,并且我试图从我的根模块 (./main.tf)

捕获相同的输出
module "kvm_instances" {
  source = "./modules/singlevm"
  for_each = var.myvms
  ...
}

output "all_ips" {
  value = ["${module.kvm_instances.*.ips}"]
 }

我收到一个错误

Error: Unsupported attribute

  on main.tf line 23, in output "all_ips":
  23:   value = ["${module.kvm_instances.*.ips}"]
  This object does not have an attribute named "ips". 

那么如何正确地从我的根模块中提取所有虚拟机的 IP 地址?提前致谢!

【问题讨论】:

    标签: terraform terraform0.12+


    【解决方案1】:

    从输出中构造的最干净的对象可能是 map(list),其中 VM 作为键,其 IP 列表作为值。您可以使用如下的 for 表达式来构建此映射:

    output "all_ips" {
      value = { for vm in keys(var.myvms) : vm => module.kvm_instances[vm].ips }
    }
    

    这将返回一个映射,其中每个 VM 是一个键,并且根据您的 output 其关联的输出 IP 地址列表将是值。

    【讨论】:

    • 感谢@Matt,我能够使用您的方法使其正常工作。我正在处理嵌套地图,并且我已经更新了我的问题以包含示例 tfvar。所以,我不得不将 var.myvms 修改为键(var.myvms)。为了他人的利益,也更新了您的答案。
    猜你喜欢
    • 2021-03-07
    • 2021-07-09
    • 2021-03-21
    • 2021-04-14
    • 2021-09-24
    • 2021-08-16
    • 2021-08-26
    • 2023-02-25
    • 2021-01-03
    相关资源
    最近更新 更多