terraform config_error ai_generated true

Error: Invalid dynamic block iterator: The iterator for a dynamic block must be a single word, not a complex expression

ID: terraform/dynamic-block-iterator-invalid

Also available as: JSON · Markdown · 中文
90%Fix Rate
85%Confidence
1Evidence
2024-01-20First Seen

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
Terraform 1.4.0 active
Terraform 1.5.0 active
Terraform 1.6.0 active

Root Cause

The dynamic block's iterator argument is set to a complex expression (like a function call or attribute reference) instead of a simple variable name.

generic

中文

动态块的 iterator 参数被设置为复杂表达式(如函数调用或属性引用),而不是简单的变量名。

Official Documentation

https://developer.hashicorp.com/terraform/language/expressions/dynamic-blocks

Workarounds

  1. 95% success Use a simple, single-word identifier for the iterator that is not already in use in the current scope. For example, if iterating over a list of tags, use 'tag' as the iterator.
    Use a simple, single-word identifier for the iterator that is not already in use in the current scope. For example, if iterating over a list of tags, use 'tag' as the iterator.
  2. 90% success If you have nested dynamic blocks, use distinct iterator names for each level, such as 'outer' and 'inner'.
    If you have nested dynamic blocks, use distinct iterator names for each level, such as 'outer' and 'inner'.

中文步骤

  1. 使用一个简单的、单词的标识符作为迭代器,且该标识符在当前作用域中未被使用。例如,如果遍历标签列表,使用 'tag' 作为迭代器。
  2. 如果有嵌套的动态块,为每一层使用不同的迭代器名称,例如 'outer' 和 'inner'。

Dead Ends

Common approaches that don't work:

  1. 90% fail

    The iterator must be a new variable name, not an existing expression. Terraform uses it to create a temporary variable within the block.

  2. 60% fail

    The default iterator 'each' works only if not already used by another dynamic block in the same resource. If 'each' is used elsewhere, it causes conflicts.

  3. 95% fail

    The iterator must be an unquoted identifier, not a string. Quoting makes it a string literal, which is not a valid variable name.