5
votes

Given this Terraform script for creating an AWS Elastic Load Balancer:

resource "aws_elb" "elb" {
  name = "${var.elb_name}"
  subnets = ["${var.subnet_ids}"]
  internal = "${var.elb_is_internal}"
  security_groups = ["${var.elb_security_group}"]

  listener {
    instance_port = "${var.backend_port}"
    instance_protocol = "${var.backend_protocol}"
    lb_port = 80
    lb_protocol = "http"
  }

  health_check {
    healthy_threshold = 2
    unhealthy_threshold = 2
    timeout = 3
    target = "${var.health_check_target}"
    interval = 30
  }

  cross_zone_load_balancing = true
}

How would it be modified to create multiple listeners?

1
Are you saying you want to control the amount of listener blocks dynamically? Because unfortunately it's not possible to do that. You'd need a separate aws_elb_listener resource that enables you to define listeners separately to the ELB and use those to configure the ELB but that resource doesn't exist (and I'm not sure it's actually practically possible). - ydaetskcoR
there is actually some activity on this issue: github.com/hashicorp/terraform/issues/9807. So while it is not possible to do now, hopefully it will make it into a future release. - Ryan E
You can't currently do this with the ELB, as the aws_elb resource only allows inline blocks for listeners. However, you can do it with the new ALB, as the aws_alb resource allows you to define listeners in separate aws_alb_listener resources. You could combine those with the count parameter and your variable to generate them dynamically. See Terraform tips & tricks: loops, if-statements, and gotchas for examples with count. - Yevgeniy Brikman

1 Answers

7
votes

You need to pass a list of maps to the listener.

listener = [{
    instance_port = "${var.backend_port}"
    instance_protocol = "${var.backend_protocol}"
    lb_port = 80
    lb_protocol = "http"
  },{
    instance_port = "${var.backend2_port}"
    instance_protocol = "${var.backend2_protocol}"
    lb_port = 8080
    lb_protocol = "http"
  }]

Alternatively,

listener = ["${var.elb_listeners}"]

where var.elb_listeners is a list of map as in the first example above.