我有一个模块,可以为名称列表创建多个资源。因此,对于名为 instances
的变量中提供的每个名称,都会创建一组资源(虚拟机、端口、卷)。
在该模块的输出中,我想要一个映射,将实例(instances
中的每个值)映射到关联端口的 IP。
这是端口的定义
resource "openstack_networking_port_v2" "this" {
for_each = var.instances
name = "port-${each.key}"
network_id = var.network_id
admin_state_up = true
security_group_ids = var.security_group_ids
fixed_ip {
subnet_id = var.subnet_id
}
}
到目前为止,我在模块的输出中有这个
output "int-port" {
value = openstack_networking_port_v2.this
}
这是我使用它的地方
int-ip : module.my-instance.int-port["${var.deployment}-my-01"].all_fixed_ips[0]
升级 terraform 后,我需要在输出中添加 sensitive = true
,因为 openstack 提供商已将某些内容标记为敏感,这将导致输出无法打印。 (我知道我可以通过 terraform output -json
获取它)
所以我想在输出中返回我需要的 IP,而不是整个对象,但我不知道如何实现。
我尝试了以下操作:
output "int-ip" {
value = openstack_networking_port_v2.this.*.all_fixed_ips[0]
}
和
output "int-ip" {
value = openstack_networking_port_v2.this[*].all_fixed_ips[0]
}
这给了我
│ Error: Unsupported attribute
│
│ on ../../modules/ext-instance-v2/outputs.tf line 24, in output "int-port":
│ 24: value = openstack_networking_port_v2.this.*.all_fixed_ips[0]
│
│ This object does not have an attribute named "all_fixed_ips".
我也尝试过
output "int-ip" {
value = {
for instance in var.instances:
instance => openstack_networking_port_v2.this["${instance}"].all_fixed_ips[0]
}
}
和
output "int-ip" {
value = {
for instance in var.instances:
instance => openstack_networking_port_v2.this[instance].all_fixed_ips[0]
}
}
这会导致该错误
│ Error: Invalid index
│
│ on ../../modules/ext-instance-v2/outputs.tf line 19, in output "int-ip":
│ 19: instance => openstack_networking_port_v2.this["${instance}"].all_fixed_ips[0]
│ ├────────────────
│ │ openstack_networking_port_v2.this is object with 9 attributes
│
│ The given key does not identify an element in this collection value.
感觉离我很近,但又遥不可及。
我不仅对解决方案感兴趣,而且对为什么我尝试过的事情没有成功的解释感兴趣。
最佳答案
由于您的 openstack_networking_port_v2.this
由于 for_each
而成为 map,因此它应该是:
output "int-ip" {
value = values(openstack_networking_port_v2.this)[*].all_fixed_ips[0]
}
更新
基于评论。最后一次尝试的正确方法是:
output "int-ip" {
value = {
for instance in keys(var.instances):
instance => openstack_networking_port_v2.this[instance].all_fixed_ips[0]
}
}
这是必需的,因为 instances
是一个 map ,但您需要一个列表。在本例中,您希望在 for-each 中使用键列表。
关于terraform - 使用 for-each 将模块中的值映射到输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67225993/