terraform 合并具有共同值的对象列表

terraform merge list of objects with common value

我有以下对象列表:

variable "accounts" {
  default =[{
          hub      = "54326543266"
          ou_name  = "test1"
          spoke    = "76547654765"
          vpc_cidr = "10.13.0.0/16"
        },
      {
          hub      = "54326543266"
          ou_name  = "test1"
          spoke    = "563904425760"
          vpc_cidr = "10.14.0.0/16"
        },
      {
          hub      = "54387632457"
          ou_name  = "test2"
          spoke    = "934960631748"
          vpc_cidr = "10.13.0.0/16"
        },
      {
          hub      = "54387632457"
          ou_name  = "test2"
          spoke    = "43892321454"
          vpc_cidr = "10.14.0.0/16"
            }
]

我想获取一个对象列表,该列表将具有相同 hubou_name 的对象合并为以下格式:

         [{
              hub      = "54326543266"
              ou_name  = "test1"
              spokes    = [ 
                 { spoke = "76547654765", vpc_cidr = "10.13.0.0/16" },
                 { spoke = "563904425760", vpc_cidr = "10.14.0.0/16" }
            },
           {
              hub      = "54387632457"
              ou_name  = "test2"
              spokes    = [ 
                 { spoke = "934960631748", vpc_cidr = "10.13.0.0/16" },
                 { spoke = "43892321454", vpc_cidr = "10.14.0.0/16" }
            }
         ]

Terraform 并不是最容易实现的,但这是我们可以做到的:

locals {
  account_groups = [
    for k, v in { for a in var.accounts : a.hub => a... } : #group by hub
    {
      "hub" : k,
      "ou_name" : v[0].ou_name,
      "spokes" : [for index, sp in v[*].spoke : { "spoke" : sp, "vpc_cidr" : v[index].vpc_cidr }] # loop again to build the spoke inner map
    }
  ]
}

首先,我们按 hub 来自 accounts 的每个项目进行分组,然后我们遍历此组图并构建具有所需格式的新列表。上面代码的输出看起来像这样:

account_groups = [
  {
    "hub" = "54326543266"
    "ou_name" = "test1"
    "spokes" = [
      {
        "spoke" = "76547654765"
        "vpc_cidr" = "10.13.0.0/16"
      },
      {
        "spoke" = "563904425760"
        "vpc_cidr" = "10.14.0.0/16"
      },
    ]
  },
  {
    "hub" = "54387632457"
    "ou_name" = "test2"
    "spokes" = [
      {
        "spoke" = "934960631748"
        "vpc_cidr" = "10.13.0.0/16"
      },
      {
        "spoke" = "43892321454"
        "vpc_cidr" = "10.14.0.0/16"
      },
    ]
  },
]