Terraform:获取带有模块和for_each的输出



我使用的是以下版本的地形:

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创建多个虚拟机,并且我正在尝试从根模块(./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地址呢?提前感谢!

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

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

它将返回一个映射,其中每个VM都是一个密钥,并且根据您的CCD_。

最新更新