terrraform Migration from map() to tomap()

Viewed 67

I inherited some old code i am triying to keep it working and pushing to tf v1.2 But, i found some problems that i am not being able to tackle.

On this code, in the dynamic condition of the module, it seems the map() function has to be changed for a tomap() one.

But it seems because this code does some kind of evaluation of lenght, the direct approach doesnt work.

resource "aws_lb_listener_rule" "forward" {
  for_each = var.lb_listener_rules_forward

  listener_arn = var.listener_arn
  priority     = each.value.priority

  action {
    type             = "forward"
    target_group_arn = aws_lb_target_group.this[each.key].arn
  }

  dynamic "condition" {
    for_each = { for k, v in map( each.key, each.value ) : k => v if length(v.host_header_values) > 0 }

    content {
      host_header {
        values = each.value.host_header_values
      }
    }
  }

  dynamic "condition" {
    for_each = { for k, v in map( each.key, each.value ) : k => v if length(v.path_pattern_values) > 0 }

    content {
      path_pattern {
        values = each.value.path_pattern_values
      }
    }
  }

}

any idea?

direct approach with tomap({ each.key = each.value }) doesnt work:

Error: Ambiguous attribute key
│ 
│   on .terraform/modules/frontend_public_website/main.tf line 167, in resource "aws_lb_listener_rule" "forward":
│  167:     for_each = { for k, v in tomap({ each.key = each.value }) : k => v if length(v.host_header_values) > 0 }
│ 
│ If this expression is intended to be a reference, wrap it in parentheses. If it's instead intended as a literal name containing periods, wrap it in quotes to create a string literal.
1 Answers

You should use the map constructor instead of either function here:

{ for k, v in { (each.key) = (each.value) } : k => v if length(v.host_header_values) > 0 }

Note that you also have an inefficient accessor for your dynamic block and should fix that accordingly too:

content {
  host_header {
    values = condition.value.host_header_values
  }
}
Related