Terraform:动态 for_each 值无效。无法在 for_each 中使用对象值列表。需要一个可迭代的集合

Som*_*hak 1 terraform terraform-provider-ibm terraform-loop

地形版本:“1.2.9”

\n

list(object({}))当具有类型并标记为的输入变量sensitive = true传递给dynamic块时,Terraform 失败并出现无效值错误for_each。\n当输入变量标记为不敏感时,不会出现该错误。

\n

输入变量如下所示:

\n
variable "sample_variable" {\n  type = list(object({\n    name = string\n    description = optional(string)\n    secure = optional(bool)\n    type = string\n    use_default = optional(bool)\n    value = string\n  }))\n  sensitive   = true\n  description = "A list of objects with sensitive values."\n  default     = []\n}\n
Run Code Online (Sandbox Code Playgroud)\n

dynamic并在资源块中消耗,for_each如下所示:

\n
resource "ibm_cloud_sample_resource" "my_resource" {\n  name                     = var.name\n  description              = var.description\n  template_env_settings    = local.env_values\n  tags                     = var.tags\n  dynamic "template_inputs" {\n    for_each = var.sample_variable\n    content {\n      name        = template_inputs.value.name\n      description = template_inputs.value.description\n      type        = template_inputs.value.type\n      value       = template_inputs.value.value\n      secure      = template_inputs.value.secure\n      use_default = template_inputs.value.use_default\n    }\n  }\n}\n
Run Code Online (Sandbox Code Playgroud)\n

错误:

\n
\xe2\x95\xb7\n\xe2\x94\x82 Error: Invalid dynamic for_each value\n\xe2\x94\x82\n\xe2\x94\x82   on main.tf line 50, in resource "ibm_cloud_sample_resource" "my_resource":\n\xe2\x94\x82   50:     for_each = var.sample_variable\n\xe2\x94\x82     \xe2\x94\x9c\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\n\xe2\x94\x82     \xe2\x94\x82 var.sample_variable has a sensitive value\n\xe2\x94\x82\n\xe2\x94\x82 Cannot use a list of object value in for_each. An iterable collection is required.\n
Run Code Online (Sandbox Code Playgroud)\n

文件中的示例值terraform.tfvars

\n
sample_variable = [ \n  { name = "api_key"\n    type = "string"\n    value = "<sensitve_api_key_value>"\n    secure = true \n  }, \n  { name = "other_variable"\n    type = "string"\n    value = "test_value_and_might_be_sensitive" \n  } \n]\n
Run Code Online (Sandbox Code Playgroud)\n

Mar*_*cin 6

您无法迭代动态块中的敏感变量。使其工作的唯一方法是使用非敏感(可能很危险!):

for_each = nonsensitive(var.sample_variable)
Run Code Online (Sandbox Code Playgroud)

因此,由您决定是否真的需要var.sample_variable敏感。如果它必须是敏感的,则您无法动态创建块,并且必须重新构建 TF 代码以不需要这样的迭代。