Terraform an ALB using module, specify target instances created by EC2 module

Viewed 169

I am trying to provision X number of EC2 instances using Terraform AWS EC2 module, then add those instances to ALB created by Terraform AWS LB module.

Instance creation:

module "ec2-test" {
  source = "terraform-aws-modules/ec2-instance/aws"

  name           = "test-"
  instance_count = 4
  use_num_suffix = true

  iam_instance_profile = aws_iam_instance_profile.base-ec2-profile.name

  ami           = var.windows_ami
  instance_type = "t3.small"
  monitoring    = true

  subnet_ids = [
    aws_subnet.private_subnet1.id, 
    aws_subnet.private_subnet2.id, 
    aws_subnet.private_subnet3.id
  ]
  vpc_security_group_ids = [
    aws_security_group.test-sg.id
  ]
  associate_public_ip_address = false

  root_block_device = [
    {
      volume_type = "gp3"
      volume_size = 30
      encrypted   = true
    }
  ]
}

This creates 4 instances, with module.ec2-test.id returning a list of created Instance IDs. Next, in the same Terraform plan, I'd like to create an internal ALB for these instances, however I cannot figure out how to specify the targets from EC2 module in the ALB module.

module "alb-test" {
  source  = "terraform-aws-modules/alb/aws"

  name = "test"

  load_balancer_type = "application"
  internal           = true

  vpc_id             = aws_vpc.test.id
  subnets            = [
    aws_subnet.private_subnet1.id,
    aws_subnet.private_subnet2.id,
    aws_subnet.private_subnet3.id
  ]
  security_groups    = [aws_security_group.alb-test.name]

  target_groups = [
    {
      name_prefix      = "test-instances-"
      backend_protocol = "HTTP"
      backend_port     = 80
      target_type      = "instance"

      targets = [
        {
          target_id = ?
          port = 80
        }
      ]
    }
  ]

  https_listeners = [
    {
      port               = 443
      protocol           = "HTTPS"
      certificate_arn    = aws_acm_certificate.test.arn
      target_group_index = 0
    }
  ]
}

What is the proper solution here? These are Windows based instances that will not scale so I do not want to create an ASG.

I tried building a map of targets like this:

  alb_targets = []
  for instance_id in module.ec2-test.id:
    alb_targets.append({
      target_id = instance_id
      port      = 80
  })

This does not work either and I am not sure why. Any insights would be appreciated.

0 Answers
Related