[英]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.