You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Terraform中depends_on未生效及AWS负载均衡目标组附件配置报错求助

解决方案

问题根源

  1. 第一个错误:aws_lb_target_group_attachment的target_id字段要求传入单个字符串(单个实例ID),你传入了数组,不符合参数类型要求。
  2. 第二个错误:for_each使用了仅在apply阶段才能确定的实例ID作为集合元素,Terraform需要在plan阶段就明确资源实例的唯一标识键,无法处理动态未知的键值。

修复方案(针对现有实例定义)

直接使用静态键映射实例ID的方式配置for_each,让Terraform在plan阶段就能确定资源实例的键集合:

resource "aws_lb_target_group_attachment" "wordpress" {
  # 用静态字符串作为键,映射到对应实例的ID
  for_each = {
    "wordpress-app-2a" = aws_instance.wordpress-app-eu-west-2a.id
    "wordpress-app-2b" = aws_instance.wordpress-app-eu-west-2b.id
  }

  target_group_arn = aws_lb_target_group.wordpress.arn
  target_id        = each.value  # 取值为对应的实例ID
  port             = 80
}

说明

  • 静态键(如wordpress-app-2a)是提前定义的,Terraform能在plan阶段确定要创建2个attachment资源实例。
  • depends_on可以省略,因为Terraform会自动识别target_id对aws_instance的依赖,确保先创建实例再绑定到目标组。

优化建议(减少重复代码)

如果后续可能增加实例数量,建议用count批量创建EC2实例,简化配置同时避免重复代码:

# 批量创建2台EC2实例
resource "aws_instance" "wordpress-app" {
  count                   = 2
  ami                     = var.bastion-ami
  instance_type           = var.bastion-instance-type
  # 按索引分配对应可用区的子网
  subnet_id               = element([aws_subnet.public-eu-west-2a.id, aws_subnet.public-eu-west-2b.id], count.index)
  vpc_security_group_ids  = [aws_security_group.bastion.id]
  associate_public_ip_address = true
  key_name                = "wordpress-key"
  user_data               = file("wordpressapp.sh")
  tags = {
    Name = "Wordpress-APP-2${chr(97 + count.index)}" # 自动生成2a、2b的名称
  }
}

# 批量绑定实例到目标组
resource "aws_lb_target_group_attachment" "wordpress" {
  # 基于批量创建的实例集合生成for_each,count是静态值,Terraform能识别集合大小
  for_each = toset([for instance in aws_instance.wordpress-app : instance.id])

  target_group_arn = aws_lb_target_group.wordpress.arn
  target_id        = each.value
  port             = 80
}

内容的提问来源于stack exchange,提问作者bkmgeorge

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.19 10:20:16