I have an target group and want to register alb as target for the target group via terraform. https://aws.amazon.com/blogs/networking-and-content-delivery/application-load-balancer-type-target-group-for-network-load-balancer/ I am sort of unable to find documentation related to that. Can anyone kindly help here?
Asked
Active
Viewed 1.1k times
4
-
I think this post can help you: https://lvthillo.com/posts/access-private-containers-on-ecs-using-privatelink/ – DenCowboy Nov 01 '21 at 16:22
1 Answers
8
Terraform documentation hasn't been fully updated to reflect the new ALB as a target group for NLB feature. Nevertheless, you should be able to do something similar to the code snippet below by looking at the AWS API reference and terraform docs:
resource "aws_vpc" "main" {
cidr_block = "10.0.0.0/16"
}
# Create ALB
resource "aws_lb" "alb" {
name = "test-alb-tf"
internal = false
load_balancer_type = "application"
security_groups = [aws_security_group.lb_sg.id]
subnets = aws_subnet.public.*.id
}
# Create ALB target group
resource "aws_lb_target_group" "alb_tg" {
name = "tf-example-lb-tg"
port = 80
protocol = "HTTP"
vpc_id = aws_vpc.main.id
}
# Create NLB
resource "aws_lb" "nlb" {
name = "test-nlb-tf"
internal = false
load_balancer_type = "network"
subnets = aws_subnet.public.*.id
}
# Create NLB target group that forwards traffic to alb
# https://docs.aws.amazon.com/elasticloadbalancing/latest/APIReference/API_CreateTargetGroup.html
resource "aws_lb_target_group" "nlb_tg" {
name = "tf-example-nlb-tg"
port = 80
protocol = "TCP"
vpc_id = aws_vpc.main.id
target_type = "alb"
}
# Create target group attachment
# More details: https://docs.aws.amazon.com/elasticloadbalancing/latest/APIReference/API_TargetDescription.html
# https://docs.aws.amazon.com/elasticloadbalancing/latest/APIReference/API_RegisterTargets.html
resource "aws_lb_target_group_attachment" "tg_attachment" {
target_group_arn = aws_lb_target_group.nlb_tg.arn
# attach the ALB to this target group
target_id = aws_lb.alb.arn
# If the target type is alb, the targeted Application Load Balancer must have at least one listener whose port matches the target group port.
port = 80
}
erik.weathers
- 821
- 1
- 8
- 13
-
2Thank you! The important thing was passing the port. if port is not passed terraform completes the apply cleanly, but the targets weren't registered. Once I passed in port the registration was successful. – Durga Oct 11 '21 at 17:21
-
1target_id of tg_attachment must be the arn of the ALB itself. The alb target_group is not useful in this example. But it is necessary to specify the port in the tg_attachment. – blang Nov 05 '21 at 22:56
-
...or at least the target_id should be the id of the ALB, not the arn – Dag Baardsen Dec 06 '21 at 13:17
-