Terraform调用带count参数的random_id属性报错问题咨询
报错根因
这个错误是Terraform资源引用的基础规则问题:
- 当资源设置了
count参数后,Terraform会将其识别为索引式资源集合,不能直接用<资源类型>.<资源名>.<属性>的格式访问顶层属性,必须指定具体实例的索引才能取到对应值。 - 你的配置里还存在更隐蔽的风险:
random_id用count按列表长度创建实例,下游的azurerm_application_insights却用for_each遍历,两套遍历逻辑的标识体系完全不匹配。就算你临时补了索引拿到值,后续只要var.application_insights的元素顺序变动、中间增删条目,就会出现随机后缀和AI实例错位,导致资源意外重建。
推荐修复方案
最稳妥的方式是把两个关联资源的遍历逻辑统一为for_each,通过相同的键做实例绑定,从根源上避免错位问题,修正后的完整配置如下:
locals { hmac_key = "${var.environmentshort}${var.hmac_key}" } resource "random_id" "application_insights_unique_suffix" { # 和下游AI资源保持完全一致的遍历集合 for_each = var.application_insights keepers = { # 每个实例的随机种子绑定当前实例key,保证不同实例生成不同后缀 rand = sha256("${local.hmac_key}-${each.key}") } byte_length = 4 } resource "azurerm_application_insights" "appi" { for_each = var.application_insights # 通过each.key匹配对应实例的随机后缀 name = "${var.productname}-${var.environmentshort}-${var.regionshort}-${random_id.application_insights_unique_suffix[each.key].hex}" location = var.resourcelocation resource_group_name = var.resourcegpname application_type = each.value["application_type"] retention_in_days = each.value["retention_in_days"] daily_data_cap_in_gb = each.value["daily_data_cap_in_gb"] tags = merge(var.rgtags, var.ars_tags) }
这种写法的优势是:只要var.application_insights里某个实例的key不变,就算调整其他实例的顺序、增删其他实例,当前实例对应的随机后缀也不会变,不会触发不必要的资源重建。
不推荐的备选方案
如果你一定要保留count写法,必须把下游的AI资源也改成count遍历,通过count.index对齐两个资源的实例顺序。但这种方式容错性极差,只要变量列表顺序变动就会导致批量资源重建,非必要不要用:
locals { hmac_key = "${var.environmentshort}${var.hmac_key}" # 先转成列表固定遍历顺序,降低错位概率 appi_list = values(var.application_insights) } resource "random_id" "application_insights_unique_suffix" { count = length(local.appi_list) keepers = { rand = sha256("${local.hmac_key}-${count.index}") } byte_length = 4 } resource "azurerm_application_insights" "appi" { count = length(local.appi_list) name = "${var.productname}-${var.environmentshort}-${var.regionshort}-${random_id.application_insights_unique_suffix[count.index].hex}" location = var.resourcelocation resource_group_name = var.resourcegpname application_type = local.appi_list[count.index]["application_type"] retention_in_days = local.appi_list[count.index]["retention_in_days"] daily_data_cap_in_gb = local.appi_list[count.index]["daily_data_cap_in_gb"] tags = merge(var.rgtags, var.ars_tags) }
内容的提问来源于stack exchange,提问作者user5813190
相关产品推荐
相关产品推荐

