无法使用 terraform 在目标组内添加多个 target_id

Not able to add multiple target_id inside targer group using terraform

我正在尝试创建目标组并使用 terraform 脚本将多台计算机附加到目标组。

我无法附加多个target_id请帮我实现这个。

尝试创建一个实例 ID 列表,然后使用计数索引进行迭代。

例如:

variable "instance_list" {
  description = "Push these instances to ALB"
  type = "list"
  default = ["i00001", "i00002", "i00003"]
}

resource "aws_alb_target_group_attachment" "test" {
  count            = "${var.instance_list}"
  target_group_arn = "${aws_alb_target_group.test.arn}"
  target_id        = "${element(var.instance_list, count.index)}"
  port             = 80
}

感谢您的快速回复。

实际上为 aws_alb_target_group_attachment 提供单独的标签,如 test1 和 test2 帮助我在一个目标组中添加多个目标实例。

resource "aws_alb_target_group_attachment" "test1" {
  target_group_arn = "${aws_alb_target_group.test.arn}"
  port             = 8080
  target_id        = "${aws_instance.inst1.id}"
}
resource "aws_alb_target_group_attachment" "test2" {
  target_group_arn = "${aws_alb_target_group.test.arn}"
  port             = 8080
  target_id        = "${aws_instance.inst2.id}"
}

下面的代码实际上对我有用。

resource "aws_alb_target_group_attachment" "test" {
  count = 3 #This can be passed as variable.
  target_group_arn = "${aws_alb_target_group.test.arn}"
  target_id         = "${element(split(",", join(",", aws_instance.web.*.id)), count.index)}"
}

参考:

https://github.com/terraform-providers/terraform-provider-aws/issues/357 https://groups.google.com/forum/#!msg/terraform-tool/Mr7F3W8WZdk/ouVR3YsrAQAJ

从 Terraform 0.12 开始,这可能只是

resource "aws_alb_target_group_attachment" "test" {
  count = length(aws_instance.test)
  target_group_arn = aws_alb_target_group.test.arn
  target_id = aws_instance.test[count.index].id
}

假设aws_instance.test returns一个list

https://blog.gruntwork.io/terraform-tips-tricks-loops-if-statements-and-gotchas-f739bbae55f9 是一个很好的参考。

我从 Terraform 创建了一个 EMR,并将多个“CORE”类型的 EC2 实例附加到一个目标组。

第一步是检索现有实例(处于“运行”状态)

data "aws_instances" "core_instances" {

  instance_state_names = ["running"]

  instance_tags = {
    "aws:elasticmapreduce:instance-group-role" = "CORE"
    "terraform" = "true"
  }

}

接下来,检索现有 VPC

data "aws_vpc" "test_vpc" {
  filter {
    name   = "tag:Name"
    values = ["your-vpc-name"]
  }
}

使用以上数据创建一个目标组,然后将实例附加到它:

resource "aws_lb_target_group" "core_lb" {
  name        = "core-emr-target-group"
  port        = 8765
  protocol    = "TCP"
  target_type = "instance"
  vpc_id      = data.aws_vpc.test_vpc.id
}

resource "aws_lb_target_group_attachment" "core_lb_instances" {
  for_each         = toset(data.aws_instances.core_instances.ids)
  target_group_arn = aws_lb_target_group.core_lb.arn
  target_id        = each.value
}

请注意,您必须将 aws_instances 返回的值(列表)转换为集合。