Dynamic block with variable number of attributes

32 views
Skip to first unread message

Mark Jaffe

unread,
Mar 3, 2021, 6:25:16 PMMar 3
to Terraform
Hi,

We're up to Terraform 0.12.30 on the way to 0.13.x, and need to make this module definition for AWS elb resource. Currently, we have:

  dynamic "listener" {
    for_each = var.listeners
    content {
      instance_port      = listener.value.instance_port
      instance_protocol  = listener.value.instance_protocol
      lb_port            = listener.value.lb_port
      lb_protocol        = listener.value.lb_protocol
    }
  }
But if our listener has SSL cert, we need to use:
  dynamic "listener" {
    for_each = var.listeners
    content {
      instance_port      = listener.value.instance_port
      instance_protocol  = listener.value.instance_protocol
      lb_port            = listener.value.lb_port
      lb_protocol        = listener.value.lb_protocol
      ssl_certificate_id = listener.value.ssl_certificate_id
    }
  }

Which, of course will not work if there is no ssl_certificate_id in the non-ssl case. What would be the appropriate syntax for a conditional in the content block?

Mark Jaffe

unread,
Mar 3, 2021, 7:24:26 PMMar 3
to Terraform
Problem solved:
  dynamic "listener" {
    for_each = var.listeners
    content {
      instance_port      = listener.value.instance_port
      instance_protocol  = listener.value.instance_protocol
      lb_port            = listener.value.lb_port
      lb_protocol        = listener.value.lb_protocol
      ssl_certificate_id = try(listener.value.ssl_certificate_id, null)
    }
  }


Reply all
Reply to author
Forward
0 new messages