Terraform自定义模块无法访问id属性问题求助
问题
我本地创建了一个复刻vault_identity_entity的自定义模块,资源定义如下:
resource "vault_identity_entity" "this" { name = var.name policies = var.policies metadata = var.metadata disabled = var.disabled external_policies = var.external_policies }
对应的outputs.tf配置:
output "entity" { description = "The entity created" value = vault_identity_entity.this }
我在另一个模块中尝试获取该模块实例的id属性,代码如下:
module "identities_memberships" { source = "../../../../path/to/identity_group_member_entity_ids" for_each = { for item in local.memberships: item.member_email => { group = item.group } } member_entity_ids = [module.identity_entities[each.key].id] group_id = module.identity_groups[each.value.group].id }
执行时报错:
│ Error: Unsupported attribute │ │ on main.tf line 101, in module "identities_memberships": │ 101: member_entity_ids = module.identity_entities[each.key].id │ ├──────────────── │ │ each.key is a string │ │ module.identity_entities is a map of object │ │ This object does not have an attribute named "id".
相关变量与模块实例化信息:
local.memberships值:
+ local_memberships = [ + { + group_name = "admins" + member_email = "john@gmail.com.com" }, + { + group_name = "admins" + member_email = "maria@gmail.com" }, + { + group_name = "operators" + member_email = "maria@gmail.com.com" }, + { + group_name = "viewers" + member_email = "adam@gmail.com.com" }, ]
module.identity_entities是自定义模块的实例化:
module "identity_entities" { source = "../../../../path/to/identity_entity" for_each = local.member_groups name = each.key depends_on = [ module.identity_groups ] }
local.member_groups值:
+ local_member_groups = { + "adam@gmail.com.com" = [ + "viewers", ] + "john@gmail.com.com" = [ + "admins", ] + "maria@gmail.com" = [ + "admins", ] + "maria@gmail.com.com" = [ + "operators", ] }
注释报错代码后,计划显示会创建含id属性的资源,但硬编码调用仍报相同错误,为何无法访问id属性?遗漏了什么?
解决方法
问题出在自定义模块的输出配置上:你的模块只对外输出了名为entity的完整资源对象,并没有直接输出id属性。Terraform模块对外暴露的属性完全由outputs.tf定义,所以直接访问module.identity_entities[each.key].id时,Terraform找不到这个输出项,就会报错。
有两种解决方式:
方式1:修改调用代码,通过entity对象访问id
把报错行的代码改成:
member_entity_ids = [module.identity_entities[each.key].entity.id]
因为module.identity_entities[each.key].entity是你输出的完整资源对象,它包含id属性。
方式2:在自定义模块中新增id输出
修改自定义模块的outputs.tf,添加单独的id输出:
output "entity" { description = "The entity created" value = vault_identity_entity.this } output "id" { description = "ID of the created identity entity" value = vault_identity_entity.this.id }
之后就可以直接用module.identity_entities[each.key].id来访问了,这种方式更直观,适合需要频繁单独获取id的场景。
内容的提问来源于stack exchange,提问作者pkaramol
相关产品推荐
相关产品推荐

