如何在 terraform 中合并两级嵌套地图?

How to merge two level nested maps in terraform?

我知道 deepmerge 有一个开放的功能请求,但我只是想看看我的用例是否有任何解决方法。让我们考虑以下局部变量:

locals {
  default = {
    class = "class1"
    options = {
       option1 = "1"
       option2 = "2"
    }
  }
  configs = {
    configA = {
        name = "A"
        max = 10
        min = 5
        enabled  = true
        options = {
            option3 = "3"
        }
    }
    configB = {
        name = "B"
        max  = 20
        min     = 10
        enabled  = false
    }
  }
}

所以我可以像这样将配置与默认值合并:

for key, config in local.configs : key => merge(local.default, config)

结果将是:

configs = {
    configA = {
        name = "A"
        class = "class1"
        max = 10
        min = 5
        enabled  = true
        options = {
            option3 = "3"
        }
    }
    configB = {
        name = "B"
        class = "class1"
        max  = 20
        min     = 10
        enabled  = false
        options = {
            option1 = "1"
            option2 = "2"
        }
    }
  }

问题是嵌套映射 (options 属性) 被 configA 完全取代,因为 merge 无法处理嵌套合并。在 terraform 1.1.3 中是否有任何解决方法?

如果您知道map的结构,您可以根据需要单独合并包含的元素。

在这种情况下,这应该有效:

merged = {
  for key, config in local.configs : key =>
  merge(
    local.default,
    config,
    { options = merge(local.default.options, lookup(config, "options", {})) }
  )
}

所以先合并顶层元素,再单独处理options