首页 > 解决方案 > Handling null with for_each

问题描述

How can I handle the following where the variables var can be null

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

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

I'm hitting

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.

标签: terraform

解决方案


You could replace the null with an empty set, list or map instead.

Changing your local to this should work:

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

As an aside you shouldn't need to use jsondecode there because var.variables must already be a serialised HCL object.


推荐阅读