Load Balancer는 여러 인스턴스에 트래픽을 분배해주기 위해서 반드시 필요한 리소스입니다. EC2 위에 올라가 있는 대부분의 서비스는 LB를 앞 단에 두는 것이 보통인데, LB의 경우에는 설정할 것이 상당히 많아 코드로 한 번 정리해놓으면 편리하게 생성/관리하실 수 있습니다.
Load Balancer는 NLB/ALB 선택해서 생성하시면 됩니다.
ALB (Application Load Balancer): Layer 7 로드밸런서로, Security Group으로 접근제어가 가능하며, URI 별로 라우팅을 할 수 있습니다.
NLB (Network Load Balancer): Layer 4 로드밸런서로, ALB보다 전송 속도는 빠르지만 Security Group으로 과거에는 접근제어가 되지 않았지만, 현재는 가능합니다.
실습에서 생성할 리소스는 아래와 같습니다.
Load Balancer
Target Group
https(443) : redirect to instance
http(80) : redirect to 443
Route53 Record
A record for ELB
Module 구성
보통 서비스를 위한 리소스는 환경별로 동일하게 생성하는 경우가 많습니다. 따라서 같은 코드를 변수만 바꿔서 사용할 수 있도록 Module을 이용하여 생성합니다.
Module을 사용할 때는 최대한 고유 명사를 없애고 변수처리하는 것이 좋습니다. 고유 명사를 변수로 대체하면 이후에 다른 서비스를
ALB 생성을 위한 리소스는 terraform/services/hello/_module/hello/alb.tf 에 있습니다. ALB 생성을 위해서는 일단 LB에 붙일 Security Group(보안 그룹)과 Load Balancer, 그리고 Target group입니다.
vim terraform/services/hello/_module/hello/alb.tf
############ Security Group For External LBresource"aws_security_group""external_lb"{name="${var.service_name}-${var.vpc_name}-ext"description="${var.service_name} external LB SG"vpc_id=var.target_vpc# Only allow access from IPs or SGs you specifiy in ext_lb_ingress_cidrs variables# If you don't want to use HTTPS then remove this blockingress{from_port=443to_port=443protocol="tcp"cidr_blocks=var.ext_lb_ingress_cidrsdescription="External service https port" }# Allow 80 portingress{from_port=80to_port=80protocol="tcp"cidr_blocks=var.ext_lb_ingress_cidrsdescription="External service http port" }egress{from_port=0to_port=0protocol="-1"cidr_blocks= ["10.0.0.0/8"]description="Internal outbound any traffic" }tags=var.sg_variables.external_lb.tags[var.shard_id]}#################### External ALBresource"aws_lb""external"{name="${var.service_name}-${var.shard_id}-ext"subnets=var.public_subnetsinternal=false# For external LB,# Home SG (Includes Office IPs) could be added if this service is internal service.security_groups= [aws_security_group.external_lb.id, ]# For HTTP service, application LB is recommended.# You could use other load_balancer_type if you want.load_balancer_type="application"tags=var.lb_variables.external_lb.tags[var.shard_id]}#################### External LB Target Groupresource"aws_lb_target_group""external"{name="${var.service_name}-${var.shard_id}-ext"port=var.service_portprotocol="HTTP"vpc_id=var.target_vpcslow_start=var.lb_variables.target_group_slow_start[var.shard_id]deregistration_delay=var.lb_variables.target_group_deregistration_delay[var.shard_id]# Change the health check settinghealth_check{interval=15port=var.healthcheck_portpath="/"timeout=3healthy_threshold=3unhealthy_threshold=2matcher="200" }tags=var.lb_variables.external_lb_tg.tags[var.shard_id]}#################### Listener for HTTP serviceresource"aws_lb_listener""internal_80"{load_balancer_arn=aws_lb.external.arnport="80"protocol="HTTP"default_action{target_group_arn=aws_lb_target_group.external.arntype="forward" }}