terraform config_error ai_generated true

Error: Invalid resource instance key: resource instance key must be a positive integer or a string

ID: terraform/resource-config-key-too-deep

Also available as: JSON · Markdown · 中文
88%Fix Rate
82%Confidence
1Evidence
2023-10-20First Seen

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
1.5.0 active
1.6.0 active

Root Cause

Using a complex expression (like a list or map) as the key in a resource instance when Terraform expects a simple integer or string.

generic

中文

在 Terraform 期望简单整数或字符串时,使用了复杂表达式(如列表或映射)作为资源实例键。

Official Documentation

https://developer.hashicorp.com/terraform/language/resources/syntax

Workarounds

  1. 90% success Simplify the key expression to a single variable or literal. For example, use 'var.environment' instead of 'var.environment[0]' if the key is meant to be a string.
    Simplify the key expression to a single variable or literal. For example, use 'var.environment' instead of 'var.environment[0]' if the key is meant to be a string.
  2. 85% success Restructure the configuration to use a for_each with a map that has simple keys, or use count with a list.
    Restructure the configuration to use a for_each with a map that has simple keys, or use count with a list.

中文步骤

  1. 将键表达式简化为单个变量或字面值。例如,如果键应为字符串,使用 'var.environment' 而不是 'var.environment[0]'。
  2. 重构配置,使用具有简单键的映射的 for_each,或使用 count 与列表。

Dead Ends

Common approaches that don't work:

  1. 90% fail

    Wrapping the expression in tostring() or tolist() does not change the fundamental type mismatch.

  2. 85% fail

    Using count.index or for_each.key in a nested resource block still fails because the key must be a literal.