13

If I get this right, lb_listener only accepts forward as valid action type. https://www.terraform.io/docs/providers/aws/r/lb_listener.html How do I configure a listener to redirect HTTP to HTTPS?

i.e. this is the desired state in elb listener:

enter image description here

LiorH
  • 18,524
  • 17
  • 70
  • 98

1 Answers1

33

This functionality was added to the AWS provider and released with 1.33.0.

Here's how you'd set the default action on a load balancer listener with the aws_lb_listener resource:

resource "aws_lb" "front_end" {
  # ...
}

resource "aws_lb_listener" "front_end" {
  load_balancer_arn = "${aws_lb.front_end.arn}"
  port              = "80"
  protocol          = "HTTP"

  default_action {
    type = "redirect"

    redirect {
      port        = "443"
      protocol    = "HTTPS"
      status_code = "HTTP_301"
    }
  }
}

You can also add redirects and fixed type responses with individual load balancer listener rules in the aws_lb_listener_rule resource:

resource "aws_lb_listener_rule" "redirect_http_to_https" {
  listener_arn = "${aws_lb_listener.front_end.arn}"

  action {
    type = "redirect"

    redirect {
      port        = "443"
      protocol    = "HTTPS"
      status_code = "HTTP_301"
    }
  }

  condition {
    host_header {
      values = ["my-service.*.terraform.io"]
    }
  }
}
ydaetskcoR
  • 53,225
  • 8
  • 158
  • 177
  • mmm... too bad :-( – LiorH Aug 09 '18 at 14:06
  • 3
    The pull request looks pretty comprehensive and at a quick glance I can't see anything wrong with it. I'd be surprised if it isn't released in the next version of the AWS provider. – ydaetskcoR Aug 09 '18 at 14:09
  • 2
    It was released, YAY! https://github.com/terraform-providers/terraform-provider-aws/issues/5344#issuecomment-415138537 – Krzysztof Kaczor Jan 10 '19 at 21:27
  • 1
    @ydaetskcoR Not sure if this has changed since you've last updated your answer but it looks like the condition now needs to look like this: condition { host_header { values = [ "my-service.*.terraform.io" ] } } – Reuben deVries Apr 30 '21 at 15:49
  • 1
    @ReubendeVries yep, that got updated in [v3 of the AWS provider](https://registry.terraform.io/providers/hashicorp/aws/latest/docs/guides/version-3-upgrade#resource-aws_lb_listener_rule). I've edited the answer to update for that. Thanks for the nudge. – ydaetskcoR May 03 '21 at 17:16
  • Whenever we have to add a redirect to port 443, we need a ssl certificate where have you specified that – Nisha Dave Jan 18 '22 at 13:47