terraform - 使用 for_each 处理 null

标签 terraform

我如何处理以下 variables var 可以为 null 的情况

locals {
  tf_variables  = (var.variables == null) ? null : jsondecode(var.variables)["variables"]
}

resource "tfe_variable" "this" {
  for_each = local.tf_variables
...
}

我在打

Error: Invalid for_each argument

  on ..\..\main.tf line 63, in resource "tfe_variable" "this":
  63:   for_each = local.tf_variables

The given "for_each" argument value is unsuitable: the given "for_each"
argument value is null. A map, or set of strings is allowed.

最佳答案

您可以将 null 替换为空集、列表或映射。

将您的本地更改为此应该有效:

locals {
  tf_variables  = (var.variables == null) ? [] : jsondecode(var.variables)["variables"]
}

另外,您不需要在那里使用 jsondecode,因为 var.variables 必须已经是序列化的 HCL 对象。

关于terraform - 使用 for_each 处理 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64826787/

相关文章:

amazon-web-services - 写入 CloudWatch 日志资源策略失败 : LimitExceededException: Resource limit exceeded

amazon-web-services - 无法通过 SSH 连接到从自动缩放组启动的 EC2 实例

Terraform 挂起且没有输出

amazon-web-services - Terraform - 在 ECS 容器定义中使用 SSM 参数

google-app-engine - 使用 Terraform 创建 App Engine 应用程序时出错

git - Terragrunt 从特定分支下载模块

amazon-web-services - 使用 Terraform 在新创建的虚拟机上创建 Docker 容器

azure - 了解terraform中的共享模块和destroy命令,如何在销毁时排除共享模块?

amazon-web-services - 在 TerraForm 的中心部分定义标签

amazon-web-services - 在 Terraform 中定义模块依赖关系