스스로 구축하는 AWS 클라우드 인프라 - 기본편을 수강하며 AWS 인프라를 Terraform으로 작성한 내용입니다.
target_group.tf
파일을 생성하고 아래와 같이 작성# Target group
resource "aws_vpclattice_target_group" "main" {
name = "alb-public-tf-${var.vpc_name}"
type = "INSTANCE"
config {
vpc_identifier = aws_vpc.main.id
port = 80
protocol = "HTTP"
protocol_version = "HTTP1"
health_check {
enabled = true
health_check_interval_seconds = 30
health_check_timeout_seconds = 5
protocol = "HTTP"
path = "/"
healthy_threshold_count = 5
unhealthy_threshold_count = 2
matcher {
value = "200"
}
}
}
tags = {
Name = "alb-public-tf-${var.vpc_name}"
}
}
# Register targets with Target group
resource "aws_vpclattice_target_group_attachment" "public_ec2" {
count = length(var.cidr_numeral_private)
target_group_identifier = aws_vpclattice_target_group.main.id
target {
id = element(aws_instance.public_ec2.*.id, count.index)
}
}
security_group.tf
파일에 아래 내용 추가# Security group for ALB
resource "aws_security_group" "alb_public_sg" {
name = "alb-public-sg"
description = "Security group for alb"
vpc_id = aws_vpc.main.id
tags = {
Name = "alb-public-sg"
}
}
# Inbound rule allowing HTTP for ALB
resource "aws_vpc_security_group_ingress_rule" "allow_http_for_alb" {
security_group_id = aws_security_group.alb_public_sg.id
cidr_ipv4 = "0.0.0.0/0"
from_port = 80
ip_protocol = "tcp"
to_port = 80
}
# Outbound rule allowing all traffic for ALB
resource "aws_vpc_security_group_egress_rule" "allow_all_outbound_traffic_for_alb" {
security_group_id = aws_security_group.alb_public_sg.id
cidr_ipv4 = "0.0.0.0/0"
ip_protocol = "-1"
}
resource "aws_lb" "alb_public" {
name = "alb-public"
load_balancer_type = "application"
internal = false
ip_address_type = "ipv4"
# Indicate which subnet in the availability zone will receive traffic
dynamic "subnet_mapping" {
for_each = toset(aws_subnet.public)
content {
subnet_id = subnet_mapping.value.id
}
}
security_groups = [aws_security_group.alb_public_sg.id]
}
resource "aws_lb_listener" "alb_public_listener" {
load_balancer_arn = aws_lb.alb_public.arn
port = 80
protocol = "HTTP"
default_action {
type = "forward"
target_group_arn = aws_lb_target_group.alb_public_tg.arn
}
tags = {
Name = "alb-public"
}
}