skip to Main Content

The issue is creating a Terraform resource using a for_each and then passing one of it’s value into a dynamic variable.

Input data –

lb_rules = tolist([
  {
    "host" = "dest-1.example.uk"
    "name" = "redirect-host"
    "path" = "/"
    "path_pattern" = tolist([
      "",
    ])
    host_header" = tolist([
      "origin-1.example.uk",
    ])
    "port" = "#{port}"
    "priority" = 5
    "protocol" = "#{protocol}"
    "status_code" = "HTTP_301"
    "type" = "dev"
  },
  {
    "host" = "dest-2.example.uk"
    "name" = "redirect-all"
    "path" = "/"
    "path_pattern" = tolist([
      "/*",
    ])
    host_header" = tolist([
      "origin-2.example.uk",
    ])
    "port" = "#{port}"
    "priority" = 100
    "protocol" = "#{protocol}"
    "status_code" = "HTTP_301"
    "type" = "stage"
  }
])

And then feed that data into the following resource –

resource "aws_lb_listener_rule" "redirect" {

  for_each = { for r in var.lb_rules : r.name => r }

  listener_arn = aws_lb_listener.default.arn
  priority     = each.value.priority

  action {
    type = "redirect"
    redirect {
      protocol    = each.value.protocol
      host        = each.value.host
      port        = each.value.port
      path        = each.value.path
      status_code = each.value.status_code
    }
  }

  condition {
    dynamic "host_header" {
      for_each = each.value.host_header 
      content {
        values = host_header.value.*.host_header
      }
    }
  }

  tags = {
    Name = each.value.name
  }

}

The above works without the dynamic variable.

The error for the dynamic variable is

Can't access attributes on a primitive-typed value (string).

Is there anything obvious missing ?

2

Answers


  1. Chosen as BEST ANSWER

    Thank you anhhq, I had to tweak your idea and this is the final work solution -

    condition {
        dynamic "host_header" {
          for_each = each.value.origin_host_header == null ? [] : each.value.origin_host_header
          content {
            values = [host_header.value]
          }
        }
      }
    

    If the value origin_host_header doesn't exist, it is passed in as null, therefore the dynamic var is not created.


  2. Try:

      condition {
        dynamic "host_header" {
          for_each = [each.value.host_header] != "" ? [each.value.host_header] : []
          content {
            values = host_header.value
          }
        }
      }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search