Application Load Balancer를 통한 이중화 네트워크 구성 (2)

Chori·2025년 1월 4일
0
post-thumbnail

스스로 구축하는 AWS 클라우드 인프라 - 기본편을 수강하며 AWS 인프라를 Terraform으로 작성한 내용입니다.


  • 웹 서버를 외부와 직접적인 통신이 가능한 Public Subnet에 두는 것은 보안 측면에서 적절하지 않음
  • 웹 서버를 외부와 직접적인 통신에 제한되어 있는 Private Subnet에 두고 이 영역에 있는 EC2 인스턴스를 타겟으로 하는 Application Load Balancer를 통해 트래픽을 분산하고 웹 서비스를 제공하도록 구성

Target group 생성

  • Private EC2 인스턴스를 타겟으로 하는 Target group 만들기
  • 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 생성

  • Application Load Balancer에 적용할 Security group 만들기
  • 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 생성

  • 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"
  }
}
  • Application Load Balancer가 인터넷에서 트래픽을 받을 수 있도록 Public Subnet에 배치
profile
전부인 것처럼, 전부가 아닌 것처럼

0개의 댓글