gpt4 book ai didi

terraform - module.db 是一个对象列表,只有在申请后才知道

转载 作者:行者123 更新时间:2023-12-05 08:29:24 24 4
gpt4 key购买 nike

rds.tf:-

module "db" {
**count = var.environment == "dev" || var.environment == "qa" ? 1 : 0**
source = "../rds"
identifier = var.db_name
engine = var.rds_engine
engine_version = var.rds_engine_version

output.tf:

output "rds_instance_endpoint" {
description = "The connection endpoint"
value = module.db.db_instance_endpoint
}

ERROR:-

Error: Unsupported attribute
on outputs.tf line 28, in output "rds_instance_endpoint":
28: value = module.db.db_instance_endpoint
module.db is a list of object, known only after apply

Can't access attributes on a list of objects. Did you mean to access attribute "db_instance_endpoint" for a specific element of the list, or across all elements of the list?

在 rds.tf 模块中声明计数时出现上述错误。如果我删除 count 那么它工作正常,不知道这个错误是什么。

最佳答案

本例中的错误信息是“无法访问对象列表上的属性”这句话,而不是“module.db is a list of object, known only after apply”;后者只是帮助您理解后面的错误消息的附加上下文。

换句话说,Terraform 告诉您 module.db 是一个对象列表并且使用 .db_instance_endpoint 是无效的( “访问属性”)在该列表上。

这里的根本问题是您有一个可能存在也可能不存在的模块对象,因此您需要向 Terraform 解释您希望如何处理它不存在的情况。

一个答案是更改您的输出值以返回一组实例端点,这些端点在开发和 QA 环境以外的环境中为空:

output "rds_instance_endpoints" {
description = "The connection endpoints for any database instances in this environment."
value = toset(module.db[*].db_instance_endpoint)
}

这里我用了the "splat" operator为模块的每个实例取 db_instance_endpoint 属性值,目前这意味着它要么是单元素集,要么是空集,视情况而定。这种方法最直接地对底层实现进行建模,并且可以让您在将来需要时自由添加此模块的其他实例,但您可能会认为这是一个多实例模块这一事实应该是一个实现细节封装在模块本身中。


另一个主要选项,确实隐藏了作为列表的底层模块的实现细节,是在存在的情况下让你的输出值为 null没有模块的实例,或者当有一个实例时是单个字符串。为此,我们可以稍微调整上面的示例以使用 the one function而不是 the toset function :

output "rds_instance_endpoints" {
description = "The connection endpoint for the database instance in this environment, if any."
value = one(module.db[*].db_instance_endpoint)
}

one 函数具有三种可能的结果,具体取决于给定集合中元素的数量:

  • 如果集合没有元素,它将返回null
  • 如果集合只有一个元素,它将只返回该元素的值。
  • 如果集合有多个元素,它将失败并显示一条错误消息。但请注意,这种结果在您的情况下是不可能的,因为 count 只能设置为零或一。

如果将此数据返回到调用模块以供在其他地方使用,则处理空值可能会很烦人,但有时它是所描述基础结构的最合理表示,因此值得额外的复杂性。特别是对于 root module 输出值,Terraform 会将空值视为根本未设置输出值,将其隐藏在 terraform apply 的消息中,等等如果您的主要动机是在用户界面中返回此信息以供人类用于某些后续操作,则第二种策略通常是最佳选择。

关于terraform - module.db 是一个对象列表,只有在申请后才知道,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70607001/

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