Terraform:使用 terraform-provider-aci 迭代嵌套 JSON 中的字符串列表

Terraform: Iterate over a list of strings in a nested JSON with terraform-provider-aci

这个问题困扰我很久了。我正在尝试使用 Terraform 和 Cisco ACI 设置一些基础设施。我现在要做的是为一个租户设置多个epg。因此,for_each 我正在迭代我的 JSON。但我不明白如何遍历 epg 键(其中包含一个字符串列表)。不可能那么难!但是我不明白。

首先是我的.json

{
   "tenants": [
 {
   "id": 1,
   "name": "kde0815",
   "bd": "bd0815",
   "vRF": "vrf0815",
   "epg": [
      "epg1"
   ],
   "_fwdCtrl": "disabled",
   "_isAttrBasedEPg": "no",
   "_matchT": "no",
   "_prefGrMemb": "unenforced"
},
 {
   "id": 97,
   "name": "kde0816",
   "bd": [
      "bd0816"  
   ],
   "vRF": "vrf0816",
   "epg": [
      "epg1",
      "epg2,
      "epg3,
      "epg4" 
   ],
   "_fwdCtrl": "disabled",
   "_isAttrBasedEPg": "no",
   "_matchT": "no",
   "_prefGrMemb": "unenforced"
}
]
}

我的resources.tf

locals {
  # get json 
  user_data = jsondecode(file("./data/aci-data_test.json"))

  # get all users
  all_users = [for tenants in local.user_data.tenants : tenants.name]

}

resource "aci_application_epg" "epgLocalName" {
  for_each               = { for inst in local.user_data.tenants : inst.id => inst }
  relation_fv_rs_bd      = aci_bridge_domain.bdLocalName[each.value.id].id
  application_profile_dn = aci_application_profile.apLocalName[each.value.id].id
  
  # dynamic "name" {
  #   for_each = each.value.epg 
  #   content {
  #     name = name.value
  #   }
  #}

}

当然这不是我的全部代码。我已经创建了 Tenants、Bridgedomains 等。 我尝试使用动态块来检查“epg”,出现两个错误

Error: Missing required argument
│ The argument "name" is required, but no definition was found
Error: Unsupported block type
│ Blocks of type "name" are not expected here.

所以我厌倦了使用第二个 for_each 循环

Error: Attribute redefined: The argument "for_each" was already set at resources.tf:54,3-11. Each argument may be set only once.

到目前为止,我了解到您仅对 modifying/filtering... 字符串使用 for 循环。有没有办法只使用for循环将字符串传递给aci_applicaton_profile中的变量“name”?

我真的被 Terraform 困住了……Python 这样做从来没有遇到过问题。 因此,如果您有任何想法,我将不胜感激。

你必须展平你的user_data。例如:

locals {
 
  flat_all_users = merge([ for id, inst in local.user_data.tenants:
          {
            for epg in inst.epg:
              "${id}-${epg}" => {
                    id = id
                    name = epg
              }
          }    
    ]...)
}

然后

resource "aci_application_epg" "epgLocalName" {
  for_each               = localflat_all_users
  relation_fv_rs_bd      = aci_bridge_domain.bdLocalName[each.value.id].id
  application_profile_dn = aci_application_profile.apLocalName[each.value.id].id
  name                   = each.value.name
}