For_each 基于映射中的值使用 for 表达式循环

For_each loop with for expression based on value in map

由于标题描述不够充分让我介绍一下我的问题。 我正在为包含 profile/endpoint/custom_domain 的 CDN 创建 DRY 模块代码。 变量 cdn_config 将包含所有 necessary/optional 参数,这些参数是基于 for_each 循环创建的。

变量看起来像这样:

variable "cdn_config" {
  profiles = {
    "profile_1" = {}
 }
 
 endpoints = {
    "endpoint_1" = {
       custom_domain = {
    }
  }
 }
}

此模块的核心正在运行 - 这意味着它将创建 cdn_profile“profile_1”,然后 cdn_endpoint“endpoint_1”将被创建并分配给然后 cdn_custom_domain 将创建此配置文件并将其分配给“endpoint_1”,因为它是“endpoint_1”地图的一部分。

然后我意识到,如果我只想创建“cdn_custom_domain”并手动指定资源 ID 怎么办?

我在想添加可选参数“standalone”会有帮助,所以它看起来像这样:

variable "cdn_config" {
  profiles = {
    "profile_1" = {}
 }

 endpoints = {
    "endpoint_1" = {
       custom_domain = {
    }
  }
    "endpoint_standalone" = {
       custom_domain = {
         standalone = true
         cdn_endpoint_id = "xxxxx"
   }
  } 
 }
}

在 azurerm_cdn_endpoint 资源创建循环中,应完全忽略具有此“独立”参数 eq true“endpoint_standalone”映射的问题。

到目前为止,这个方向是我唯一的猜测,显然,它不起作用 - 如果我添加“endpoint_standalone”,它会抱怨没有指定所有必需的参数,所以它肯定会找到它。

resource "azurerm_cdn_endpoint" "this" {

for_each = {for k in keys(var.cdn_config.endpoints) : k => var.cdn_config.endpoints[k] if lookup(var.cdn_config.endpoints[k],"standalone",null) != "true"}

如果你能解决这个问题,我将不胜感激。

您正在比较 bool 类型和 string 类型,因此逻辑比较总是 return false:

for_each = {for k in keys(var.cdn_config.endpoints) : k => var.cdn_config.endpoints[k] if lookup(var.cdn_config.endpoints[k],"standalone",null) != true }

虽然我们在这里,但我们还可以改进这个for表达式:

for_each = { for endpoint, params in var.cdn_config.endpoints : endpoint => params if lookup(params.custom_domain, "standalone", null) != true }