从循环另一个模块 terraform 获取输出 instance_id

Get outputs instance_id from loop another module terraform

当我使用 for_each 创建时如何获取我的模块 ec2 的实例 ID,我需要 instance_id 我的模块 tgroup 以分配或加入特定目标组中的新实例。

我的模块 ec2

resource "aws_instance" "ProductionServer" {
    count                       = length(var.SubnetServer)
    ami                         = module.CreateAMI.AMIId.id
    instance_type               = var.TypeServer
    subnet_id                   = var.SubnetServer[count.index]
}

ec2/outputs.tf

output "InstanceId" {
    value = aws_instance.ProductionServer
    description = "get value id"
  
}

和我的模块 tgroup

resource "aws_alb_target_group_attachment" "TgProdRegister" {
    for_each         = module.GetInstanceId.InstanceId.id
    target_group_arn = var.TgroupArn
    target_id        = each.value
    port             = var.TgPort 

    depends_on = [ module.GetInstanceId ]
  
}

GetInstanceId是指模块ec2

由于您对实例使用 count,要将它们的 ID return 作为 list,您必须执行以下操作:

output "InstanceId" {
    value = aws_instance.ProductionServer[*].id
    description = "get value id"
}

那么对于目标群体来说,它将是:

resource "aws_alb_target_group_attachment" "TgProdRegister" {
    count            = length(module.GetInstanceId)
    target_group_arn = var.TgroupArn
    target_id        = module.GetInstanceId.InstanceId[count.index]
    port             = var.TgPort 
}

如果可能,购买您应该考虑将实例放置在自动缩放组 (ASG) 中的方式。