tail -f /dev/null

産まれたばかりの仔羊. If you haven't had any obstacles lately, you're not challenging. be the worst.

Terraform: 1resource loop 内に unique な list を渡す

env

terraform ver. 0.12.28

procedure

for_eachsetproduct を利用し, 1つの aws_alb_target_group_attachment に複数の EC2 instance id を渡す.

alb.tf

resource "aws_alb_target_group" "alb_target_group" {
  for_each             = var.alb_target_group
  name                 = each.value.name
  port                 = each.value.port
  protocol             = each.value.protocol
  vpc_id               = each.value.vpc_id
  deregistration_delay = each.value.deregistration_delay

  health_check {
    interval            = ...
  }
}

# setproduct() find all unique combinations of elements in a number of different collections.
# https://www.terraform.io/docs/configuration/functions/setproduct.html
resource "aws_alb_target_group_attachment" "alb_target_group_attachment" {
  for_each = {
    for pair in setproduct(keys(aws_alb_target_group.alb_target_group), var.alb_target_group_attachment.instance_ids) :
    "${pair[0]}:${pair[1]}" => {
      target_group = aws_alb_target_group.alb_target_group[pair[0]]
      instance_id  = pair[1]
      port         = aws_alb_target_group.alb_target_group[pair[0]].port
    }
  }
  target_group_arn = each.value.target_group.arn
  target_id        = each.value.instance_id
  port             = each.value.port
}

alb.tfvars

alb_target_group = {
  test-001 = {
    name                 = "test-001"
    port                 = 80
    protocol             = "HTTP"
    vpc_id               = "vpc-xxx"
    deregistration_delay = 300
    health_check = {
      interval            = ...
    }
  }
  test-002 = {
    name                 = "test-002"
    port                 = 8080
    protocol             = "HTTP"
    vpc_id               = "vpc-xxx"
    deregistration_delay = 300
    health_check = {
      interval            = ...
    }
  }
}

alb_target_group_attachment = {
  instance_ids = [
    "i-xxx", # instance-001
    "i-xxx", # instance-002
  ]
}

variables.tf

variable "alb_target_group" {}

variable "alb_target_group_attachment" {}