【问题标题】:Get outputs instance_id from loop another module terraform从循环另一个模块 terraform 获取输出 instance_id
【发布时间】:2021-12-04 13:00:27
【问题描述】:

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

我的模块 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

【问题讨论】:

    标签: amazon-web-services terraform terraform-provider-aws


    【解决方案1】:

    由于您对实例使用 count,要将它们的 id 作为列表返回,您必须这样做:

    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) 的方式。

    【讨论】:

    • hai @Marcin,感谢您之前的回答,如果我的变量列表子网=> 3,它对我有用,但如果不是,我会收到这样的错误。我的变量中还缺少什么吗? Error: Invalid index │ │ on tgroup/tgroup.tf line 8, in resource "aws_alb_target_group_attachment" "TgProdRegister": │ 8: target_id = module.GetInstanceId.InstanceId[count.index] │ ├──────────────── │ │ count.index is 2 │ │ module.GetInstanceId.InstanceId is tuple with 2 elements │ │ The given key does not identify an element in this collection value.
    • @Noobers “它不像那种情况” - 抱歉,我不明白。你的问题没有任何条件。这似乎是一个新问题,我建议使用新代码和您拥有的“条件”提出新问题。
    • 对不起@Marcin 我的错误,我的意思是如果插入我的列表子网,如SubnetServer = ["subnet-08xxx","subnet-082xxxx","subnet-084xxxx" ],它对我有用,但如果它的列表子网只有 2 个子网,如SubnetServer = ["subnet-08xxx","subnet-082xxxx" ],那么我得到了上述错误
    • @Noobers 你可以做element(var.SubnetServer, count.index)
    猜你喜欢
    • 1970-01-01
    • 2022-07-11
    • 2018-04-12
    • 2019-10-06
    • 2021-01-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多