스스로 구축하는 AWS 클라우드 인프라 - 기본편을 수강하며 AWS 인프라를 Terraform으로 작성한 내용입니다.
target_group.tf
파일에 아래 내용 추가# Target group for private ec2 instances
resource "aws_lb_target_group" "alb_private_tg" {
name = "alb-private-tg-${var.vpc_name}"
vpc_id = aws_vpc.main.id
target_type = "instance"
port = 80
protocol = "HTTP"
protocol_version = "HTTP1"
health_check {
protocol = "HTTP"
path = "/"
enabled = true
healthy_threshold = 5
unhealthy_threshold = 2
timeout = 5
interval = 30
matcher = "200"
}
tags = {
Name = "alb-private-tf-${var.vpc_name}"
}
}
# Register private ec2 instances with Target group
resource "aws_lb_target_group_attachment" "private_ec2" {
for_each = {
for k, v in aws_instance.private_ec2 : k => v # type casting: list to map
}
target_group_arn = aws_lb_target_group.alb_private_tg.arn
target_id = each.value.id
port = 80
}
security_group.tf
파일에 아래 내용 추가# Security group for private ALB
resource "aws_security_group" "alb_private_sg" {
name = "alb-private-sg"
description = "Secutiry group for private alb"
vpc_id = aws_vpc.main.id
tags = {
Name = "alb-private-sg"
}
}
# Inbound rule allowing HTTP for private ALB
resource "aws_vpc_security_group_ingress_rule" "allow_http_for_private_alb" {
security_group_id = aws_security_group.alb_private_sg.id
cidr_ipv4 = "0.0.0.0/0"
from_port = 80
ip_protocol = "tcp"
to_port = 80
}
# Outbound rule allowing all traffic for private ALB
resource "aws_vpc_security_group_egress_rule" "allow_all_outbound_traffic_for_private_alb" {
security_group_id = aws_security_group.alb_private_sg.id
cidr_ipv4 = "0.0.0.0/0"
ip_protocol = "-1"
}
application_load_balancer.tf
파일에 아래 내용 추가resource "aws_lb" "alb_private" {
name = "alb-private"
load_balancer_type = "application"
internal = false
ip_address_type = "ipv4"
security_groups = [aws_security_group.alb_private_sg.id]
# Indicate which subnet in the availability zone will receive traffic
dynamic "subnet_mapping" {
for_each = toset(aws_subnet.public_for_ec2)
content {
subnet_id = subnet_mapping.value.id
}
}
}
resource "aws_lb_listener" "alb_private_listener" {
load_balancer_arn = aws_lb.alb_private.arn
port = 80
protocol = "HTTP"
default_action {
type = "forward"
target_group_arn = aws_lb_target_group.alb_private_tg.arn
}
tags = {
Name = "alb-private"
}
}