How can I iterate through a map variable in terraform

非 Y 不嫁゛ 提交于 2020-06-28 14:34:26

问题


Im trying to iterate through a variable type map and i'm not sure how to

This is what i have so far

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}"]
}

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


回答1:


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 ...
}

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 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.




回答2:


Can you try:

resource "aws_route_53_record" "proxy_dns" {
    count = "${length(var.account_name)}"
    name = "proxy-${var.account_name[count.index]}-dns
}



回答3:


Make the variable a list instead of a map. Maps are used to reference a name to a value. Lists are better for iterating over via a count method.

variable "account_name" {
  type = "list"
  default = {"accountA","accountB"}
}
resource "aws_route_53_record" "proxy_dns" {
    count = "${length(var.account_name)}"
    zone_id = "${infrastructure.zone_id}"
    name = "proxy-${element(var.account_name, count.index)}-dns
    type = CNAME
    ttl = 60
    records = ["{records.dns_name}"]
}


来源:https://stackoverflow.com/questions/57503110/how-can-i-iterate-through-a-map-variable-in-terraform

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!