缩小地图(地图(地图(列表(字符串))))地形

Reduce map(map(map(list(string)))) terraform

您好,有什么巧妙的方法可以将 map(map(map(list(string)))) 转换为具有 terraform 的 map(map(list(string))) 。

这是我的输入结构:

   exception_expr_rule = {
   "project" = {
     "user" = {
       sqli-stable = [
         "value",
       ],
       xss-stable = [
         "value",
         "value",
         "value"
       ],
       rce-stable = [
         "value"
       ],
       ...... = []
     },
     "user2" = {
       xss-stable = [
         "value",
       ],
       other-subsubkey = [
         "value"
       ],
       other-subsubkey = [
         "value"
       ],
       other-subsubkey = [
         "value"
       ],
      }
      "userN" = {....}
   }}

这就是我想要的样子:

exception_expr_rule = {
 "project.user" = {
    sqli-stable = [
      "value",
    ],
    xss-stable = [
      "value",
      "value",
      "value"
    ],
    rce-stable = [
      "value"
    ]
  },
"project.user2" = {
    xss-stable = [
      "value",
    ],
    other-subsubkey = [
       "value"
     ],
     .....
   }
"project.userN" = {.....}
}

你们能帮我实现这个吗?

我试过

    exception_expr_rule_list = flatten([
    for projects,value in var.expr_rule_list : [
      for user_name,exceptions in value: {
          key = "${projects}.${user_name}"
          value = exceptions
        }
    ]
  ])

但不是我想要的

有点棘手,但 flattenfor 循环的组合可以帮助您实现目标。

我已经在控制台中使用 Terraform v0.14.5 对此进行了测试。

首先我定义了一个变量来复制你的输入结构:

variable "exception_expr_rule" {
  type = map

  default = {
    "project" = {
      "user" = {
        sqli-stable = [
          "value"
        ],
        xss-stable = [
          "value",
          "value",
          "value"
        ],
        rce-stable = [
          "value"
        ]
      }
    }
  }
}

然后我创建了一个新的 new 局部变量,它合并并展平了它:

locals {
  new = flatten([
    for key in keys(var.exception_expr_rule): [
      for subkey, subvalue in var.exception_expr_rule[key]: {
        "${key}.${subkey}" = subvalue
      }
    ]
  ])
}

如果我通过 local.new[0] 访问它,我会得到所需的输出:

> local.new[0]
{
  "project.user" = {
    "rce-stable" = [
      "value",
    ]
    "sqli-stable" = [
      "value",
    ]
    "xss-stable" = [
      "value",
      "value",
      "value",
    ]
  }
}

解决了

    new = {for pair in flatten([ 
       for key in keys(var.exception_expr_rule_list): [ 
          for subkey, subvalue in var.exception_expr_rule_list[key]: { 
              key = "${key}.${subkey}" 
              value = subvalue 
          } 
        ] 
       ]): "${pair.key}" => pair.value 
}