如何遍历 terraform 中的地图变量 [英] How can I iterate through a map variable in terraform
问题描述
我正在尝试遍历变量类型映射,但我不确定如何
Im trying to iterate through a variable type map and i'm not sure how to
这是我目前所拥有的
在我的 main.tf 中:
In my main.tf:
resource "aws_route_53_record" "proxy_dns" {
count = "${length(var.account_name)}"
zone_id = "${infrastructure.zone_id}"
name = "proxy-${element(split(",", var.account_name), count.index)}-dns
type = CNAME
ttl = 60
records = ["{records.dns_name}"]
}
在我的 variables.tf 中
And in my variables.tf
variable "account_name" {
type = "map"
default = {
"account1" = "accountA"
"account2" = "accountB"
}
}
我希望能够使用不同的帐户名创建多个资源
I want to be able to create multiple resources with the different account names
推荐答案
如果您使用的是 Terraform 0.12.6 或更高版本,则可以使用 for_each
而不是 count
为地图中的每个元素生成一个实例:
If you are using Terraform 0.12.6 or later then you can use for_each
instead of count
to produce one instance for each element in your map:
resource "aws_route53_record" "proxy_dns" {
for_each = var.account_name
zone_id = infrastructure.zone_id
name = "proxy-${each.value}-dns"
# ... etc ...
}
for_each
优于 count
的主要优势在于 Terraform 将通过地图中的键识别实例,因此您将获得像 aws_route53_record 这样的实例.proxy_dns["account1"]
而不是 aws_route53_record.proxy_dns[0]
,因此您可以在将来使用 Terraform 知道每个元素属于哪个特定实例的情况下从地图中添加和删除元素.
The primary advantage of for_each
over count
is that Terraform will identify the instances by the key in the map, so you'll get instances like aws_route53_record.proxy_dns["account1"]
instead of aws_route53_record.proxy_dns[0]
, and so you can add and remove elements from your map in future with Terraform knowing which specific instance belongs to each element.
each.key
和 each.value
当 for_each
为用过的.它们分别计算当前地图元素的键和值.
each.key
and each.value
in the resource type arguments replace count.index
when for_each
is used. They evaluate to the key and value of the current map element, respectively.
这篇关于如何遍历 terraform 中的地图变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!