简体   繁体   中英

How to use for_each with iterator in dynamic block in Terraform?

I am trying to do this basically:

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
}

I am outputting lb from a submodule in Terraform, and trying to use that in the parent module in a for_each array, with a custom iterator name. It is giving me this error:

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

But it DOES have that attribute, it's an aws_lb . What am I doing wrong in the usage of this for_each and module setup, and how do I fix it? Thank you very much!

If I change it to this it seems to work:

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

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

From the docs :

The iterator object (setting in the example above) has two attributes :

key is the map key or list element index for the current element. If the for_each expression produces a set value then key is identical to value and should not be used.

value is the value of the current element.

Based on that, in the content , you should used lb.value["arn"] , as per example . Thus, the following could be tried:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM