在.tf.json资源中使用for_each时出现JSON值类型错误
Fixing Terraform JSON for_each Value Type Error
Let's break down what's going wrong and fix your gsuite_user resource configuration step by step.
Why You're Seeing the Error
The error message points to an incorrect JSON structure for your resource block. In Terraform's JSON syntax:
- The
resource.<type>object expects instance names mapped to their configurations (a valid JSON object). - You tried placing
for_eachdirectly at the top level of thegsuite_userobject, which doesn't fit Terraform's JSON schema. Additionally, yourprimary_emailexpression was incorrectly referencing non-existentvar.first_name/var.last_namevariables instead of using theeach.valuefrom youremployee_map.
Corrected Configuration
Here's the fixed main.tf.json with proper structure and corrected variable references:
{ "resource": { "gsuite_user": { "*": { "for_each": "${var.employee_map}", "change_password_next_login": true, "name": { "family_name": "${each.value.last_name}", "given_name": "${each.value.first_name}" }, "password": "password", "primary_email": "${each.value.first_name}.${each.value.last_name}@email", "lifecycle": { "ignore_changes": ["password", "change_password_next_login"] } } } } }
Key Changes Made:
- Added the
"*"wildcard key: In Terraform JSON, this tells Terraform we're defining a dynamic resource template to be repeated viafor_each, rather than a single named resource. - Moved
for_eachinto the wildcard block: This placesfor_eachin the correct location as a parameter for the dynamic resource template. - Fixed
primary_emailexpression: Changed${var.first_name}.${var.last_name}@emailto${each.value.first_name}.${each.value.last_name}@emailto reference the first/last name from each entry in youremployee_map. - Properly formatted JSON: Split the code into multiple lines for readability (minified works too, but this helps catch syntax errors).
Verify Your Variables File
Your variables file is mostly correct, but adding an explicit type definition improves validation and clarity:
{ "variable": { "employee_map": { "type": "map(object({ first_name = string last_name = string }))", "default": { "john.doe": { "first_name": "john", "last_name": "doe" }, "jane.doey": { "first_name": "jane", "last_name": "doey" } } } } }
Test the Fix
Run these commands to validate and apply your configuration:
terraform init terraform validate terraform plan
You should see Terraform plan to create two gsuite_user instances, one for each entry in your employee_map.
内容的提问来源于stack exchange,提问作者Benjamin Waters
相关产品推荐
相关产品推荐

