Terraform:引用每个.钥匙或每个.在调用变量时模块中的值



我正试图实现(也许是错误的手段)这样的东西。我希望能够在Azure中创建几种类型的端点(例如KV, SA)。

module "endpoints" {
source = "./modules/private_endpoint"
for_each = toset(var.endpoint_type)
private_connection_resource_id  = "var.${each.value}.private_connection_resource_id"

地点:Endpoint_type是一个端点列表(其值为"storage_account"),private_connection_resource_id在map(any)中,它看起来像(还有其他值,但我认为它们在这一点上不重要):

storage_account = {
private_connection_resource_id = #VALUE
...

private_connection_resource_id = "var.${each.value}.private_connection_resource_id;——这被翻译成文字字符串(var.storage_account.private_connection_resource_id),在那里我希望它被翻译成确切的值-存储帐户的id(它在tfvars中硬编码)。

提前感谢你的任何提示!

编辑:看来我和他们一样笨。应该稍微改变一下地图的
endpoint_type = {
storage_account = {
private_connection_resource_id = #VALUE
...

和ref在模块中调用:each.value.private_connection_resource_id

不能在字符串中构造表达式,然后对其求值。Terraform总是先解析完整的配置,然后在解析完后再执行。

如果你想根据键动态查找值,那么映射是最合适的数据结构。例如,您可以像这样定义一个输入变量endpoint_typesendpoints:

variable "endpoint_types" {
type = map(object({
private_connection_resource_id = string
}})
}
variable "endpoints" {
type = map(object({
type = string
}))
}

我对上述示例的意图是,endpoints对象中的type属性是endpoint_types中另一个映射的查找键。

当你用for_each定义module块时,你将首先参考var.endpoints,然后根据var.endpoint_types所选择的键查找适当的端点类型:

module "endpoints" {
source   = "./modules/private_endpoint"
for_each = var.endpoints
private_connection_resource_id = var.endpoint_types[each.value.type].private_connection_resource_id
}

外部模块的用户需要提供端点的映射和描述这些端点可能具有的所有可能类型的映射,如下所示:

endpoints = {
storage_1 = {
type = "storage"
}
storage_2 = {
type = "storage"
}
other_1 = {
type = "other"
}
}
endpoint_types = {
storage = {
private_connection_resource_id = "something"
}
other = {
private_connection_resource_id = "something_else"
}
}

最新更新