Json 文件作为计数变量,terraform
我正在尝试传递一个有3个名称的文件,用于地形资源中的计数,文件如下 userlist.jsonJson 文件作为计数变量,terraform,json,linux,amazon-web-services,terraform,Json,Linux,Amazon Web Services,Terraform,我正在尝试传递一个有3个名称的文件,用于地形资源中的计数,文件如下 userlist.json ["pepe", "pipo", "popo"] 我试图用terraform做的是根据json文件的长度创建X个数量的策略,但是我得到了以下错误 Error: Invalid index │ │ on main.tf line 3, in resource "aws_iam_policy" "policy
["pepe", "pipo", "popo"]
我试图用terraform做的是根据json文件的长度创建X个数量的策略,但是我得到了以下错误
Error: Invalid index
│
│ on main.tf line 3, in resource "aws_iam_policy" "policy":
│ 3: name = file("files/userlist.json"[count.index])
│ ├────────────────
│ │ count.index is a number, known only after apply
│
│ This value does not have any indices.
main.tf
resource "aws_iam_policy" "policy" {
count = length(file("userlist.json"))
name = file("userlist.json"[count.index])
path = var.path
description = var.description
policy = file(var.policy_json_location[count.index])
}
我得到以下错误
Error: Invalid index
│
│ on main.tf line 3, in resource "aws_iam_policy" "policy":
│ 3: name = file("files/userlist.json"[count.index])
│ ├────────────────
│ │ count.index is a number, known only after apply
│
│ This value does not have any indices.
terraform似乎不喜欢我在计数中传递文件而不是字符串的方式,即使在那里声明了“file”如果我正确理解了这个问题,您可能需要使用
jsondecode(file(“test.json”)
而不是file(“test.json”)
下面的代码片段演示了该行为
resource "null_resource" "test_res" {
count = length(jsondecode(file("test.json")))
}
output "file_content" {
value = jsondecode(file("test.json"))
}
output "test_res" {
value = null_resource.test_res
}
产出的价值很高
file_cont = [
"pipo",
"pepo",
"pepe",
]
test_res = [
{
"id" = "6672935723139812109"
"triggers" = tomap(null) /* of string */
},
{
"id" = "7815380621246912709"
"triggers" = tomap(null) /* of string */
},
{
"id" = "6843574097785729573"
"triggers" = tomap(null) /* of string */
},
]
未经请求的建议:也可使用terraform console
调试这些问题,例如:
$ terraform console
> file("test.json")
<<EOT
["pipo", "pepo", "pepe"]
EOT
> jsondecode(file("test.json"))
[
"pipo",
"pepo",
"pepe",
]
$terraform控制台
>文件(“test.json”)
必须添加jsondecode并移动count.index才能工作,这是最终的资源工作
resource "aws_iam_policy" "policy" {
count = length(jsondecode(file(var.policy_name)))
name = jsondecode(file(var.policy_name))[count.index]
description = jsondecode(file(var.policy_name))[count.index]
policy = file(jsondecode(file(var.policy_json_location))[count.index])
tags = var.tags
path = var.path
}
你有没有考虑过用for_代替count?这也消除了使用索引的需要。类似这样的东西
resource "aws_iam_policy" "policy" {
for_each = to_set(jsondecode(file(var.policy_name)))
name = each.value
description = each.value
policy =(jsondecode(file(var.policy_json_location))[each.key])
tags = var.tags
path = var.path
}
这个例子很可能并没有为您提供完整的解决方案,但主要是为了演示for_如何在地形中工作。
另请参阅
由于有两个不同的json文件,您可能需要确保它们之间的键匹配,但这应该会使它更加健壮。我不知道terraform是什么,但在main.tf中,如本文所示,我看到了所有的7行,甚至10行。您想用文件(“userlist.json”[count.index])
实现什么?您希望它能做什么?为什么假设count有一个.index
属性?对我来说,length
操作(当然是针对其他语言的操作)的结果应该是一个简单的int
?它没有完全符合我的要求,但给了我一个提示,多亏了你,我可以修复它