I think this may just be a fundamental lack of knowledge (I’m new to Terraform). But I’m struggling to figure out what should go in target_id. I feel it wants the id of just one instance but I’m trying to attach the load balancer to an autoscaling group but I’ve tried id and arn of the auto scaling group but to no avail.
resource "aws_autoscaling_group" "ec2_autoscaling" {
name = "EC2 Autoscaling Group"
max_size = 4
min_size = 2
health_check_grace_period = 10
desired_capacity = 2
vpc_zone_identifier = [aws_subnet.TFSubnetPublic1.id, aws_subnet.TFSubnetPublic2.id]
target_group_arns = [aws_lb_target_group.alb_target_group.arn]
launch_template {
id = aws_launch_template.autoscaling_launch_template.id
}
}
resource "aws_lb" "KenobiTFALB" {
name = "KenobiTF-alb"
security_groups = [aws_security_group.alb_sg.id]
subnets = [aws_subnet.TFSubnetPublic1.id, aws_subnet.TFSubnetPublic2.id]
tags = {
Name = "Terraform ALB"
}
}
resource "aws_lb_target_group" "alb_target_group" {
name = "Terraform-ALB-Target-Group"
port = 80
protocol = "HTTP"
vpc_id = aws_vpc.KenobiTFVPC.id
health_check {
healthy_threshold = 3
interval = 60
unhealthy_threshold = 3
matcher = "200"
}
}
resource "aws_lb_target_group_attachment" "alb_target_group_attachment" {
target_group_arn = aws_lb_target_group.alb_target_group.arn
target_id = aws_lb.KenobiTFALB.id
port = 80
}
(Sorry I feel indentation has failed somehow)
2
Answers
When you are using an Auto-Scaling Group, you don’t manage attaching the instances to the Auto-Scaling Group at all. The Auto-Scaling Group handles that for you. That’s why you provide the Target Group’s ARN to the Auto-Scaling Group.
You should completely delete the
resource "aws_lb_target_group_attachment"
resource from your Terraform code, as it is only needed when you are creating individual instances via Terraform without an Auto-Scaling Group.In your case, you don’t need this aws_lb_target_group_attachment block as you have already configured your ASG with a target group in the aws_autoscaling_group resource block.
So whenever a new instance is spawned, it will directly get registered in the target group.