Terraform version - 0.14
I am creating a simple module that will create a NLB/Listner/Target_group/Target_group_attachment
I am struggling to combine this with a EC2 module. The Target_group_attachment needs to take the Id’s of the EC2’s that are created in the EC2 module. But I am unsure how to do this.
##################################
# Network Loadbalancer #
##################################
resource "aws_lb" "this" {
name = var.nlb_name
internal = var.internal
load_balancer_type = "network"
subnets = var.nlb_subnets
enable_deletion_protection = var.enable_deletion_protection
enable_cross_zone_load_balancing = var.enable_cross_zone_load_balancing
tags = var.tags # specific tags?
}
################################
# Target Group #
################################
resource "aws_lb_target_group" "this" {
for_each = var.nlb_target_group
name = each.value.nlb_target_name
port = each.value.nlb_target_port
protocol = each.value.nlb_target_protocol
target_type = each.value.nlb_target_type
vpc_id = var.vpc_id
health_check {
healthy_threshold = var.health_check_healthy_threshold
unhealthy_threshold = var.health_check_unhealthy_threshold
interval = var.health_check_interval
protocol = var.health_check_protocol
}
tags = var.tags
}
################################
# Target Group Attachment #
################################
resource "aws_lb_target_group_attachment" "this" {
for_each = var.nlb_target_group
target_group_arn = aws_lb_target_group.this[each.key].arn
target_id = var.target_id[each.value.id]
port = var.target_group_attachment_port
}
################################
# Listner #
################################
resource "aws_lb_listener" "this" {
for_each = var.nlb_target_group
load_balancer_arn = aws_lb.this.arn
port = var.nlb_listner_port
protocol = var.nlb_listner_protocol
default_action {
type = var.nlb_listner_default_action_type
target_group_arn = aws_lb_target_group.this[each.key].arn
}
}
var.target_id & nlb_target_group are below
variable "target_id" {
type = map(object({
id = string
availability_zone = string
tags = map(string)
}))
}
variable "nlb_target_group" {
type = map(object({
nlb_target_name = string
nlb_target_port = string
nlb_target_protocol = string
nlb_target_type = string
}))
}
Which I know could be simplified but I might want to bring more values from the EC2 module.
In the resource “aws_lb_target_group_attachment” “this” resource I need to know how to use both the var.target_id and loop through the var.target_id for the target id.