aws_lb_target_group_attachment:将多个实例附加到每个 target_group

Mac*_*ers 5 terraform terraform-provider-aws

我每个 NLB 有多个 target_groups,我需要将多个实例附加到每个 target_group。将target_id在作为一个字符串aws_lb_target_group_attachment资源,我看不出有什么简单的方法来实现这一目标。这就是我正在做的 atm:

变量文件

variable "nlb_listeners" {
  default = [
    {
      protocol     = "TCP"
      target_port  = "80"
      health_port  = "1936"
    },
    {
      protocol     = "TCP"
      target_port  = "443"
      health_port  = "1936"
    }
  ]
}
Run Code Online (Sandbox Code Playgroud)

实例.tf

// Get the instance ids of the NLB members  
data "aws_instances" "nlb_insts" {
  instance_tags = {
   Name = "${var.vpc_names[var.idx]}${var.inst_role}0*"
  }
  instance_state_names = ["running", "stopped"]
}

// EC2 instances
resource "aws_instance" "insts" {
  count         = var.inst_count
  instance_type = var.inst_type
  .......
}
Run Code Online (Sandbox Code Playgroud)

平衡器.tf

// Creates the target-group
resource "aws_lb_target_group" "nlb_target_groups" {
  count                = length(var.nlb_listeners)
  name                 = "nlb-tgr-${lookup(var.nlb_listeners[count.index], "target_port")}"
  deregistration_delay = var.deregistration_delay
  port                 = lookup(var.nlb_listeners[count.index], "target_port")
  protocol             = lookup(var.nlb_listeners[count.index], "protocol")
  vpc_id               = var.vpc_ids[var.idx]

  health_check {
    port                = lookup(var.nlb_listeners[count.index], "health_port")
    protocol            = lookup(var.nlb_listeners[count.index], "protocol")
    interval            = var.health_check_interval
    unhealthy_threshold = var.unhealthy_threshold
    healthy_threshold   = var.healthy_threshold
  }
}

// Attach the target groups to the instance(s)
resource "aws_lb_target_group_attachment" "tgr_attachment" {
  count            = length(var.nlb_listeners)
  target_group_arn = element(aws_lb_target_group.nlb_target_groups.*.arn, count.index)
  target_id        = [for sc in range(var.inst_count) : data.aws_instances.nlb_insts.ids[sc]]
  port             = lookup(var.nlb_listeners[count.index], "target_port")
}
Run Code Online (Sandbox Code Playgroud)

所以,我收到了这个错误:

错误:属性值类型不正确

在 ../../modules/elb/balencer.tf 第 31 行,在资源 "aws_lb_target_group_attachment" "tgr_attachment": 31: target_id = [for sc in range(2) : data.aws_instances.nlb_insts.ids[sc]]

属性“target_id”的值不合适:需要字符串。

任何人都知道我如何实现这一目标?

Rum*_*les 1

快速查看您的代码,我会说这是给您带来错误的错误:

data.aws_instances.nlb_insts.ids[sc]
Run Code Online (Sandbox Code Playgroud)

应该:

data.aws_instances.nlb_insts[sc].ids
Run Code Online (Sandbox Code Playgroud)

索引位于资源上,然后您从资源中获取 id,在您的情况下,您试图获取所有资源的所有 id,然后获取该资源的索引,这不是这样做的方法!