【问题标题】:terraform merge list of objects with common value具有共同值的对象的terraform合并列表
【发布时间】:2022-01-25 16:21:12
【问题描述】:

我有以下对象列表:

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"
            }
]

我想获取一个对象列表,将具有相同hub 和ou_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 terraform-provider-aws terraform0.12+


    【解决方案1】:

    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"
          },
        ]
      },
    ]
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-10-22
      • 2021-03-15
      • 2020-06-20
      • 1970-01-01
      • 1970-01-01
      • 2017-06-24
      • 2021-02-09
      • 1970-01-01
      相关资源
      最近更新 更多