Resource: aws_lb_target_group_attachment

Provides the ability to register instances and containers with an Application Load Balancer (ALB) or Network Load Balancer (NLB) target group. For attaching resources with Elastic Load Balancer (ELB), see the aws_elb_attachment resource.

Example Usage

Basic Usage

resource "aws_lb_target_group_attachment" "test" {
  target_group_arn = aws_lb_target_group.test.arn
  target_id        = aws_instance.test.id
  port             = 80
}

resource "aws_lb_target_group" "test" {
  # ... other configuration ...
}

resource "aws_instance" "test" {
  # ... other configuration ...
}

Lambda Target

resource "aws_lambda_permission" "with_lb" {
  statement_id  = "AllowExecutionFromlb"
  action        = "lambda:InvokeFunction"
  function_name = aws_lambda_function.test.function_name
  principal     = "elasticloadbalancing.amazonaws.com"
  source_arn    = aws_lb_target_group.test.arn
}

resource "aws_lb_target_group" "test" {
  name        = "test"
  target_type = "lambda"
}

resource "aws_lambda_function" "test" {
  # ... other configuration ...
}

resource "aws_lb_target_group_attachment" "test" {
  target_group_arn = aws_lb_target_group.test.arn
  target_id        = aws_lambda_function.test.arn
  depends_on       = [aws_lambda_permission.with_lb]
}

Registering Multiple Targets

resource "aws_instance" "example" {
  count = 3
  # ... other configuration ...
}

resource "aws_lb_target_group" "example" {
  # ... other configuration ...
}

resource "aws_lb_target_group_attachment" "example" {
  # covert a list of instance objects to a map with instance ID as the key, and an instance
  # object as the value.
  for_each = {
    for k, v in aws_instance.example :
    k => v
  }

  target_group_arn = aws_lb_target_group.example.arn
  target_id        = each.value.id
  port             = 80
}

Argument Reference

The following arguments are required:

The following arguments are optional:

Attribute Reference

This resource exports the following attributes in addition to the arguments above:

Import

You cannot import Target Group Attachments.