You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Terraform:合并列表映射生成唯一对象集解决部署重复问题

解决Terraform中azurerm_role_assignment的重复对象问题

问题场景

部署azurerm_role_assignment资源时,原始变量输出存在assignment_name与hostpool重复的对象,需要生成唯一对象集来适配如下资源配置:

// Assign AVD role to scope and group
resource "azurerm_role_assignment" "avd_jumphost_sa" {
  for_each = local.per_assignment_helper_map  
  scope              = azurerm_storage_account.avd_jumphost[each.value.hostpool].id
  role_definition_name = "Storage File Data SMB Share Contributor"
  principal_id       = data.azuread_group.avd_jumphost[each.value.assignment_name].id
}

无效尝试

  • 使用distinct、merge函数处理后,输出的列表格式无法匹配principal_id参数要求
  • 尝试flatten处理,仍未得到可用的结构

可行解决方案

通过在local块中生成唯一标识键,结合zipmap函数生成符合for_each要求的映射表:

locals {
  // 原始包含重复项的角色分配数据
  raw_role_assignments = var.role_assignments

  // 基于assignment_name和hostpool组合去重,得到唯一对象列表
  unique_role_assignments = distinct([
    for item in local.raw_role_assignments : {
      assignment_name = item.assignment_name
      hostpool        = item.hostpool
    }
  ])

  // 生成唯一键,用于构建映射表的键值
  unique_keys = [
    for item in local.unique_role_assignments : "${item.assignment_name}-${item.hostpool}"
  ]

  // 生成适配for_each的最终映射表
  per_assignment_helper_map = zipmap(local.unique_keys, local.unique_role_assignments)
}

生成的local.per_assignment_helper_map会以assignment_name-hostpool作为唯一键,对应去重后的对象为值,完美适配azurerm_role_assignment的for_each需求,彻底解决重复资源部署问题。

内容的提问来源于stack exchange,提问作者Richard

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.29 10:03:31