terraform - For_each 循环,带有基于映射中值的 for 表达式

标签 terraform terraform-provider-azure

由于标题描述性不够,让我介绍一下我的问题。 我正在为包含 profile/endpoint/custom_domain 的 CDN 创建 DRY 模块代码。 变量 cdn_config 将保存所有必需/可选参数,这些参数是基于 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” map 。

然后我意识到,如果我只想创建“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 资源创建循环中应完全忽略此“standalone”参数 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 类型与字符串类型进行比较,因此逻辑比较将始终返回 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 }

关于terraform - For_each 循环,带有基于映射中值的 for 表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71147530/

相关文章:

azure - 如何将新创建的子网引用到 terraforn azure 中的其他模块

azure - Terraform azure keyVault SetSecret - 禁止访问被拒绝

terraform - 强制Terraform仅从本地磁盘安装提供程序,从而禁用Terraform Registry

amazon-web-services - 在没有 VPC 端点或 0.0.0.0/0 规则的 AWS 上运行 Terraform

terraform - 从头开始 AWS EKS - terraform 还是 eksctl?

azure - 什么可能导致 Terraform "forget"它已经在管理它创建的资源?

azure - 如何用文本替换地形中的变量?

amazon-ec2 - 使用 Terraform 创建可达性分析器路径

azure - 通过自动化为多个资源组上的托管身份添加 RBAC 角色

azure - 运行 terraform init 后无法查看 Terraform 提供程序文件