[英]file as a variable for count, terraform
我试图传递一个具有 3 个名称的文件,以便在 terraform 资源中使用 count,该文件如下
用户列表.json
["pepe", "pipo", "popo"]
我试图用 terraform 做的是根据 json 文件的长度创建 X 数量的策略,但我收到以下错误
主文件
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 不喜欢我传递文件而不是字符串的方式,即使在那里声明了“文件”
如果我正确理解了这个问题,您可能需要使用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",
]
必须添加 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_each 而不是计数? 这也消除了使用索引的需要。 沿着这些思路
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_each 在 Terraform 中如何工作。 另请参阅Terraform for_each 文档
由于有两个不同的 json 文件,您可能需要确保它们之间的键匹配,但这应该使它更健壮。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.