首页 > 解决方案 > 如何在 Terraform 的动态块中使用 for_each 和迭代器?

问题描述

我基本上正在尝试这样做:

module "california" {
  source = "./themodule"
  # ...
}

module "oregon" {
  source = "./themodule"
  # ...
}

resource "aws_globalaccelerator_endpoint_group" "world" {
  # ...
  dynamic "endpoint_configuration" {
    for_each = [
      module.california.lb,
      module.oregon.lb
    ]
    iterator = lb
    content {
      endpoint_id = lb.arn
      weight = 100
    }
  }
}

# themodule/main.tf
resource "aws_lb" "lb" {
  # ...
}

output "lb" {
  value = aws_lb.lb
}

我正在lb从 Terraform 中的子模块输出,并尝试在for_each数组中的父模块中使用它,并使用自定义iterator名称。它给了我这个错误:

This object does not have an attribute named "arn".

但它确实具有该属性,它是一个aws_lb. 我在使用这个和模块设置时做错了什么,我该for_each如何解决?非常感谢你!

如果我将其更改为此它似乎可以工作:

resource "aws_globalaccelerator_endpoint_group" "world" {
  listener_arn = aws_globalaccelerator_listener.world.id

  endpoint_configuration {
    endpoint_id = module.california.lb.arn
    weight = 100
  }
}

标签: amazon-web-servicesmoduleiteratorterraform

解决方案


文档

迭代器对象(上例中的设置)有两个属性

key是当前元素的映射键或列表元素索引。如果 for_each 表达式产生一个设置值,则 key 与 value 相同,不应使用。

value是当前元素的值。

基于此,在 中content,您应该lb.value["arn"]按照示例使用。因此,可以尝试以下方法:

    content {
      endpoint_id = lb.value["arn"]
      weight = 100
    }

推荐阅读