使用 for_each 处理 null

Dar*_*Var 5 terraform

我该如何处理以下variablesvar 可以为空的情况

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

resource "tfe_variable" "this" {
  for_each = local.tf_variables
...
}
Run Code Online (Sandbox Code Playgroud)

我正在打

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.
Run Code Online (Sandbox Code Playgroud)

yda*_*coR 9

您可以将 替换null为空集、列表或地图。

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

locals {
  tf_variables  = (var.variables == null) ? [] : jsondecode(var.variables)["variables"]
}
Run Code Online (Sandbox Code Playgroud)

顺便说一句,您不需要jsondecode在那里使用,因为var.variables它必须已经是序列化的 HCL 对象。