我正在将Terraform v12.19与aws提供程序v2.34.0一起使用。 想象一下,我生成了一个带有计数值的资源:
resource "aws_iam_role" "role" {
count = length(var.somevariable)
name = var.somevariable[count.index]
}
稍后,我想以这种方式引用一个特定的资源实例。 g。:
resource "aws_iam_role_policy_attachment" "polatt" {
role = aws_iam_role.role["TheRoleNameIWant"].id
policy_arn = "arn:aws:iam::aws:policy/..."
}
我不知道索引,我只能依靠变量提供的名称。那是因为变量的值是由外部来源提供的,并且顺序可能会更改...
任何想法如何做到这一点?
答案 0 :(得分:1)
您应该能够使用index
terraform函数来完成此操作。
这是一个使用null_resources
进行测试的最小示例
locals {
role_names = [
"role-a",
"role-b",
"role-c",
"role-d",
]
target_role_name = "role-c"
}
resource "null_resource" "hi" {
count = length(local.role_names)
}
output "target_resource" {
value = null_resource.hi[index(local.role_names, local.target_role_name)].id
}
output "all_resources" {
value = [for r in null_resource.hi : r.id]
}
例如,输出
all_resources = [
"4350570701002192774",
"9173388682753384584",
"1634695740603384613",
"2098863759573339880",
]
target_resource = 1634695740603384613
因此,我想您的示例如下
resource "aws_iam_role_policy_attachment" "polatt" {
role = aws_iam_role.role[index(var.somevariable, "TheRoleNameIWant")].id
policy_arn = "arn:aws:iam::aws:policy/..."
}
您在下面的评论中提到,实际上,您的数据结构比名称列表更为复杂。我只想提及您可以从JSON结构派生名称。
假设您有类似以下内容
variable "role_values" {
value = [
{
name = "foo",
other = "details",
fields = 3
},
{
name = "bar",
other = "yet more details",
fields = 3
}
]
}
您可以通过使用本地和较新的for
循环TF 0.12提供的名称来仅获取名称
locals {
role_names = [for role in var.role_values: role.name]
}
这样,您不必将名称存储两次。