gpt4 book ai didi

amazon-web-services - 启用计数时创建 Terraform 输出

转载 作者:行者123 更新时间:2023-12-03 23:49:46 27 4
gpt4 key购买 nike

我正在尝试为 Terraform 中已设置计数的资源创建一个 output.tf。当计数为 1 时,一切正常,但是当计数为 0 时,它不会:

如果我像这样创建输出

output "ec2_instance_id" {
value = aws_instance.ec2_instance.id
}

它出错

because aws_instance.ec2_instance has "count" set, its attributes must be accessed on specific instances.



但是,将其更改为
output "ec2_instance_id" {
value = aws_instance.ec2_instance[0].id
}

适用于计数为 1,但当计数为 0 时给出

aws_instance.ec2_instance is empty tuple

The given key does not identify an element in this collection value.



所以我看到了 this post并尝试
output "ec2_instance_id" {
value = aws_instance.ec2_instance[count.index].id
}

但这给

The "count" object can be used only in "resource" and "data" blocks, and only when the "count" argument is set.



什么是正确的语法?

最佳答案

只要你只关心1个或0个实例,就可以访问整个列表可以使用splat expression aws_instance.ec2_instance[*].idjoin函数和一个空字符串,根据资源是否被创建而产生 ID 或空字符串。

output "ec2_instance_id" {
value = join("", aws_instance.ec2_instance[*].id)
}

例子:
variable "thing1" {
default = [
{ id = "one" }
]
}

variable "thing2" {
default = []
}

output "thing1" {
value = join("", var.thing1[*].id)
}

output "thing2" {
value = join("", var.thing2[*].id)
}

结果是
➜ terraform apply

Apply complete! Resources: 0 added, 0 changed, 0 destroyed.

Outputs:

thing1 = one
thing2 =

关于amazon-web-services - 启用计数时创建 Terraform 输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59375652/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com