【问题标题】:Unable to loop over list using for_each无法使用 for_each 遍历列表
【发布时间】:2020-03-17 15:50:55
【问题描述】:

我想保留一个 IP 然后使用它。如果我为每个 IP 创建一个单独的 google_compute_address 块,它运行良好。但是由于我想让代码尽可能的干燥和优化,我正在学习如何循环和使用for_each

我的 ma​​in.tf 看起来像这样

module "nat" {
  source  = "../../modules/nat"

  reserved_ips = [
    {
      name = "gke-frontend-prod-lb"
      ip = "10.238.232.10"
    },
    {
      name = "gke-frontend-test-lb"
      ip = "10.238.232.11"
    }
  ]
} 

如您所见,我想形成一个具有名称和 IP 的保留 IP 列表。

现在让我们看看我的模块

我的 variables.tf 看起来像

variable "reserved_ips" {
  type        = list(object({
    name = string
    ip = string
  }))
  description = <<EOF
Reserved IPs.
EOF
}

我的模块的 ma​​in.tf 看起来像

locals {
  ips = {
    # for_each needs transform to map
    for ip in var.reserved_ips : "${ip.name}" => "${ip.ip}"
  }
}


resource "google_compute_address" "gke-frontend" {
  for_each = local.ips

  name         = "${each.value.name}"
  subnetwork   = "mysubnet"
  address_type = "INTERNAL"
  address      = "${each.value.ip}"
}

但是运行代码给了我

Error: Unsupported attribute

  on ../../modules/nat/main.tf line 11, in resource "google_compute_address" "gke-frontend":
  11:   name         = "${each.value.name}"
    |----------------
    | each.value is "10.238.232.10"

This value does not have any attributes.


Error: Unsupported attribute

  on ../../modules/nat/main.tf line 11, in resource "google_compute_address" "gke-frontend":
  11:   name         = "${each.value.name}"
    |----------------
    | each.value is "10.238.232.11"

This value does not have any attributes.


Error: Unsupported attribute

  on ../../modules/nat/main.tf line 14, in resource "google_compute_address" "gke-frontend":
  14:   address      = "${each.value.ip}"
    |----------------
    | each.value is "10.238.232.10"

This value does not have any attributes.


Error: Unsupported attribute

  on ../../modules/nat/main.tf line 14, in resource "google_compute_address" "gke-frontend":
  14:   address      = "${each.value.ip}"
    |----------------
    | each.value is "10.238.232.11"

This value does not have any attributes.

我很困惑我到底错过了什么。

【问题讨论】:

    标签: terraform terraform-provider-gcp


    【解决方案1】:

    问题是您的 ips 本地将列表转换为 map(string)(即带有字符串值的映射)

    locals {
      ips = {
        # for_each needs transform to map
        for ip in var.reserved_ips : "${ip.name}" => "${ip.ip}"
      }
    }
    

    请注意,在=&gt; 的右侧有"${ip.ip}"

    for_each 循环遍历map 时,它将each.key 分配给每个键(string)和each.value 分配给映射中的每个对应值(在这种情况下,"${ip.ip} 也是@987654332 @)。

    所以,我认为在这种情况下你想要的是如下内容

      # ...
      name         = each.key
      # ...
      address      = each.value
      # ...
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-06-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多