Search code examples
amazon-web-servicesamazon-ec2terraformcloudload-balancing

how to add a load balancer to an ec2 instance using terraform


I am developing inside an ec2 instance and I just added a load balancer to ec2 using terraform but now i am getting a 504 Gateway Time-out error message on the browser when i try to access the load balancer dns address, also i noticed that the target group is unhealthy so the health check fail.

I have the following load balancer configuration:

resource "aws_lb" "alb" {
  name               = "backend-lb"
  internal           = false
  load_balancer_type = "application"
  security_groups    = [aws_security_group.lb_sg.id]
  idle_timeout       = 60
  subnets            = [element(aws_subnet.public.*.id, 0), element(aws_subnet.public.*.id, 1)]
}

resource "aws_lb_target_group" "alb_target_group" {
  name        = "backend-tg"
  port        = 8000
  protocol    = "HTTP"
  target_type = "ip"
  vpc_id      = aws_vpc.main.id

  health_check {
    enabled = true
    path = "/"
    port = "8000"
    protocol = "HTTP"
    healthy_threshold = 3
    unhealthy_threshold = 2
    interval = 90
    timeout = 20
    matcher = "200"
  }

  depends_on = [aws_lb.alb]
}

resource "aws_lb_listener" "http" {
  load_balancer_arn = aws_lb.alb.arn
  port              = "80"
  protocol          = "HTTP"

  default_action {
    type             = "forward"
    target_group_arn = aws_lb_target_group.alb_target_group.arn

  }
}

resource "aws_lb_target_group_attachment" "one" {
  target_group_arn = aws_lb_target_group.alb_target_group.arn
  target_id        = aws_instance.ec2.private_ip
  port             = 8000
}

please note that i used .private_ip in aws_lb_target_group_attachment target_id because i was facing the error Error: Error registering targets with target group: ValidationError: The IP address '....foo id or arn' is not a valid IPv4 address when trying to use .id or .arn.

Is there something that i am doing wrong here, is it the appropriate way to add a load balancer to an ec2 instance?


Solution

  • First you need to fix the target_type in your aws_lb_target_group. Change it from ip to instance. Or just delete that setting since instance is the default.

    Then target ID should be the ID of the instance, not the IP address. The code should be:

    target_id        = aws_instance.ec2.id
    

    After that if it still doesn't work you need to verify that the security group of the EC2 instance allows ingress on port 8000 from the load balancer, that software on the EC2 instance is actually listening for web requests on port 8000, and that an HTTP GET request on port 8000 of the EC2 instance returns status code 200.