먼저, ASG를 배포하기 위한 사전 준비사항은 앞서 수행했던 ASG의 VPC, 서브넷, 라우팅테이블과 data.tf, provider.tf가 동일하게 쓰였다.
또한, 폴더 구조는 다음과 같다.
앞서, 인스턴스에 단순한 웹서버를 구동시켰으므로 현 로드밸런서 배포에서는 ALB를 사용한다.
ALB를 구성하기 위해서는 아래와 같은 구성이 필요하다.
resource "aws_lb" "terraform-lb" {
name = "terraform-lb"
load_balancer_type = "application"
subnets = [aws_subnet.terraform-subnet1.id, aws_subnet.terraform-subnet2.id]
security_groups = [aws_security_group.terraform-alb-sg.id]
}
# 기본 HTTP 포트인 80번 포트 수신
resource "aws_lb_listener" "http" {
load_balancer_arn = aws_lb.terraform-lb.arn
port = 80
protocol = "HTTP"
# 리스너 규칙과 일치하지 않는 요청은 기본값인 단순한 404 페이지 오류를 반환
default_action {
type = "fixed-response"
fixed_response {
content_type = "text/plain"
message_body = "404: page not found"
status_code = 404
}
}
}
resource "aws_security_group" "terraform-alb-sg" {
name = "terraform-alb-sg"
vpc_id = aws_vpc.terraform-vpc.id
# 인바운드 "HTTP" 트래픽 허용
ingress {
from_port = 80
to_port = 80
protocol = "tcp"
cidr_blocks = ["0.0.0.0/0"]
}
# 모든 아웃바운드 트래픽 허용 - 로드밸런서가 health check를 수행하기 위함
egress {
from_port = 0
to_port = 0
protocol = "-1"
cidr_blocks = ["0.0.0.0/0"]
}
}
# HTTP 요청을 인스턴스에 주기적으로 요청 전송하여 인스턴스 상태 점검
resource "aws_lb_target_group" "terraform-alb-tg" {
name = "terraofrm-alb-tg"
port = 80
protocol = "HTTP"
vpc_id = aws_vpc.terraform-vpc.id
health_check {
path = "/"
protocol = "HTTP"
matcher = "200"
interval = 15
timeout = 3
healthy_threshold = 2
unhealthy_threshold = 2
}
}
# 모든 경로와 일치하는 요청을 ASG가 포함된 대상 그룹으로 보냄
resource "aws_lb_listener_rule" "terraform-lbrule" {
listener_arn = aws_lb_listener.http.arn
priority = 100
condition {
path_pattern {
values = ["*"]
}
}
action {
type = "forward"
target_group_arn = aws_lb_target_group.terraform-alb-tg.arn
}
}
output "terraform-alb-dns-name" {
value = aws_lb.terraform-lb.dns_name
description = "The domain name of the load balancer"
}
health_check_type을 ELB로 설정하고 대상 그룹을 alb.tf의 대상그룹으로 설정하였다.
resource "aws_launch_configuration" "terraform-launconfig" {
image_id = data.aws_ami.ubuntu.id
instance_type = "t2.micro"
security_groups = [aws_security_group.terraform-alb-sg.id]
user_data = <<-EOF
#!/bin/bash
echo "Hello, World" > index.html
nohup busybox httpd -f -p 80 &
EOF
# Autu Scaling Group에서 시작 구성을 사용할 때 필요
lifecycle {
create_before_destroy = true
}
}
resource "aws_autoscaling_group" "terraform-asg" {
launch_configuration = aws_launch_configuration.terraform-launconfig.name
vpc_zone_identifier = [aws_subnet.terraform-subnet1.id, aws_subnet.terraform-subnet2.id]
target_group_arns = [aws_lb_target_group.terraform-alb-tg.arn]
health_check_type = "ELB"
min_size = 2
max_size = 5
tag {
key = "name"
value = "terraform-terraform-asg"
propagate_at_launch = true
}
}