我正在尝试在.tf.json文件内的资源中使用新的for_each
目标是能够通过员工地图并以编程方式为每个人生成一个gsuite_user,而不必重新声明每个资源(也是因为模块尚未循环)
{
"resource": {
"gsuite_user": {
"for_each": "${var.employee_map}",
"employee": {
"change_password_next_login": true,
"name": {
"family_name": "${each.value.last_name}",
"given_name": "${each.value.first_name}"
},
"password": "password",
"primary_email" :"${var.first_name}.${var.last_name}@email",
"lifecycle": {
"ignore_changes": ["password", "change_password_next_login"]
}
}
}
}
我遇到以下错误:
Error: Incorrect JSON value type
on ../modules/employees/main.tf.json line 4, in resource.gsuite_user:
4: "for_each": "${var.employee_map}",
Either a JSON object or a JSON array is required, representing the contents of
one or more "resource" blocks.
我的变量文件是
{
"employee_map": {
"john.doe": {
"first_name": "john",
"last_name": "doe"
},
"jane.doey": {
"first_name": "jane",
"last_name": "doey"
}
}
}
答案 0 :(得分:0)
出现此错误是因为资源声明中缺少嵌套级别。
以下面的本机语法声明为例:
resource "gsuite_user" "employee" {
for_each = var.employee_map
change_password_next_login = true
# etc, etc
}
请注意,上面的for_each
参数与resource
参数以及随后的所有其他参数一起位于change_password_next_login
块内。为了模仿JSON,类似的"for_each"
属性必须位于表示该块的JSON对象中:
{
"resource": {
"gsuite_user": {
"employee": {
"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" :"${var.first_name}.${var.last_name}@email",
"lifecycle": {
"ignore_changes": ["password", "change_password_next_login"]
}
}
}
}
}
如果将for_each
直接放在gsuite_user
对象中,则JSON解码器会假定您正在尝试声明resource "gsuite_user" "for_each"
块,因此尝试将"${var.employee_map}"
解释为该块的主体。这是无效的,因为块的主体必须始终表示为JSON对象。 (它也可能是一个数组,在这种情况下,它将声明一个或多个块,但这在这种情况下没有意义,因为资源块标签在模块内必须是唯一的。)