Terraform中aws_lb_target_group_attachment配置问题求助
Terraform中aws_lb_target_group_attachment关联Auto Scaling Group的正确方式
核心问题分析
你当前的配置存在两个关键错误:
aws_lb_target_group_attachment的target_id填成了负载均衡器的ID,这完全不符合该资源的用途——这个资源是用来绑定单个EC2实例到目标组的,target_id必须是EC2实例的ID,而非ALB或ASG的标识。- 试图用
aws_lb_target_group_attachment关联Auto Scaling Group是方向错误,ASG和目标组的联动根本不需要这个资源。
正确实现方式
你的Auto Scaling Group配置中已经包含了target_group_arns = [aws_lb_target_group.alb_target_group.arn]这行代码,它的作用就是让ASG自动管理实例在目标组的注册与注销:
- 当ASG扩容创建新EC2实例时,会自动将实例注册到指定的目标组;
- 当ASG缩容销毁实例时,会自动将实例从目标组中移除。
因此,你需要删除整个aws_lb_target_group_attachment.alb_target_group_attachment资源,它不仅多余,还因填错target_id导致配置无效。
修正后的完整配置
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] # 这行实现ASG与目标组的自动关联 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" } }
额外注意事项
- 确保启动模板中EC2实例的安全组允许目标组的健康检查流量(80端口)以及ALB的访问流量;
- 如果ASG使用ELB健康检查,需保证目标组的健康检查配置与实例的服务状态匹配,避免实例被误标记为不健康。
内容的提问来源于stack exchange,提问作者MikeMac
相关产品推荐
相关产品推荐

