provider "aws" { region = var.aws_region } # ------------------------------- # ALB Security Group # ------------------------------- resource "aws_security_group" "alb_sg" { name = "${var.alb_name}-sg" description = "Security group for ALB" vpc_id = var.vpc_id ingress { from_port = 80 to_port = 80 protocol = "tcp" cidr_blocks = ["0.0.0.0/0"] } ingress { from_port = 443 to_port = 443 protocol = "tcp" cidr_blocks = ["0.0.0.0/0"] } egress { from_port = 0 to_port = 0 protocol = "-1" cidr_blocks = ["0.0.0.0/0"] } } # ------------------------------- # Application Load Balancer # ------------------------------- resource "aws_lb" "alb" { name = var.alb_name load_balancer_type = "application" subnets = var.subnet_ids security_groups = [aws_security_group.alb_sg.id] } # ------------------------------- # Target Group # ------------------------------- resource "aws_lb_target_group" "tg" { name = var.target_group_name port = var.target_port protocol = "HTTPS" vpc_id = var.vpc_id target_type = "instance" health_check { path = "/" matcher = "200-499" interval = 30 timeout = 5 healthy_threshold = 2 unhealthy_threshold = 2 } } # ------------------------------- # HTTP Listener → HTTPS Redirect # ------------------------------- resource "aws_lb_listener" "http" { load_balancer_arn = aws_lb.alb.arn port = 80 protocol = "HTTP" default_action { type = "redirect" redirect { port = "443" protocol = "HTTPS" status_code = "HTTP_301" } } } # ------------------------------- # HTTPS Listener → Target Group # ------------------------------- resource "aws_lb_listener" "https" { load_balancer_arn = aws_lb.alb.arn port = 443 protocol = "HTTPS" ssl_policy = "ELBSecurityPolicy-2016-08" certificate_arn = var.certificate_arn default_action { type = "forward" target_group_arn = aws_lb_target_group.tg.arn } } resource "aws_autoscaling_group" "existing_eks_asg" { name = var.existing_asg_name min_size = var.asg_min_size max_size = var.asg_max_size desired_capacity = var.asg_desired_capacity launch_template { id = var.existing_asg_launch_template_id version = "$Latest" } lifecycle { ignore_changes = [ launch_template, mixed_instances_policy, vpc_zone_identifier, target_group_arns, health_check_type, health_check_grace_period, termination_policies, enabled_metrics, tag, ] } } # ------------------------------- # Attach Existing ASG to Target Group # ------------------------------- resource "aws_autoscaling_attachment" "asg_to_tg" { autoscaling_group_name = aws_autoscaling_group.existing_eks_asg.name lb_target_group_arn = aws_lb_target_group.tg.arn }