我很难弄清楚如何为该代码创建的每个目标组资源进行输出。我希望能够在其他模块中分别引用每个人。听起来像for_each将其存储为地图,所以我的问题是如何获取targetgroup1和targetgroup2的arn? Terraform通常使用资源名称来引用输出,因此在这种情况下,以及如何引用这些单独的arn方面,我都很费劲。我还需要将输出工作到for_each中还是可以将其放入output.tf文件中?
locals {
target_groups_beta = {
targetgroup1 = {
name = "example",
path = "/",
environment = "Beta"
}
targetgroup2 = {
name = "example2",
path = "/",
environment = "Beta"
}
}
}
resource "aws_lb_target_group" "target-group" {
for_each = local.target_groups_beta
name = "example-${each.value.name}-"
port = 80
protocol = "HTTP"
vpc_id = var.vpc-id
deregistration_delay = 5
tags = {
Environment = "${each.value.environment}"
}
health_check{
healthy_threshold = 2
unhealthy_threshold = 2
timeout = 10
interval = 15
path = each.value.path
}
}
在没有键值的output.tf文件中尝试执行此操作时收到以下错误,但是当我输入诸如value =“ $ {aws_lb_target_group.target-group [0] .arn}”之类的错误时,它说这是无效的。没有以下键值的错误:
错误:缺少资源实例密钥
在modules \ targetgroups \ output.tf第2行上,在输出“ tg_example_beta”中: 2:值=“ $ {aws_lb_target_group.target-group.arn}”
因为aws_lb_target_group.target-group设置了“ for_each”,其属性 必须在特定实例上访问。
例如,要与引用资源的索引相关联,请使用: aws_lb_target_group.target-group [each.key]
答案 0 :(得分:1)
生成的aws_lb_target_group.target-group
将是一个映射,其键值为targetgroup2
和targetgroup1
。
因此,要获取各个目标组的详细信息,您可以执行以下操作:
output "target-group1-arn" {
value = aws_lb_target_group.target-group["targetgroup1"].arn
}
要将两者都作为地图返回:
output "target-groups-arn-alternatice" {
value = {for k, v in aws_lb_target_group.target-group: k => v.arn}
}
target-groups-arn-alternatice = {
"targetgroup1" = "arn:aws:elasticloadbalancing:us-east-1:xxxx:targetgroup/example-example/285b26e15221b113"
"targetgroup2" = "arn:aws:elasticloadbalancing:us-east-1:xxxx:targetgroup/example-example2/075bd58359e4c4b2"
}
要同时返回两个列表(顺序与keys
函数的顺序相同):
output "target-groups-arn" {
value = values(aws_lb_target_group.target-group)[*].arn
}
target-groups-arn = [
"arn:aws:elasticloadbalancing:us-east-1:xxxx:targetgroup/example-example/285b26e15221b113",
"arn:aws:elasticloadbalancing:us-east-1:xxxx:targetgroup/example-example2/075bd58359e4c4b2",
]