resource "aws_lb" "main" { name = "main-alb" internal = false load_balancer_type = "application" security_groups = [aws_security_group.alb_sg.id] subnets = var.public_subnets enable_deletion_protection = false idle_timeout = 60 tags = { Name = "main-alb" } } resource "aws_lb_listener" "http" { count = var.certificate_arn == "" ? 1 : 0 load_balancer_arn = aws_lb.main.arn port = 80 protocol = "HTTP" default_action { type = "forward" target_group_arn = aws_lb_target_group.main.arn } } resource "aws_lb_listener" "http_redirect" { count = var.certificate_arn != "" ? 1 : 0 load_balancer_arn = aws_lb.main.arn port = 80 protocol = "HTTP" default_action { type = "redirect" redirect { host = "#{host}" path = "/" port = "443" protocol = "HTTPS" query = "#{query}" status_code = "HTTP_301" } } } resource "aws_lb_listener" "https" { count = var.certificate_arn != "" ? 1 : 0 load_balancer_arn = aws_lb.main.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.main.arn } } resource "aws_lb_target_group" "main" { name = "main-target-group" port = 80 protocol = "HTTP" vpc_id = var.vpc_id health_check { path = "/labs/health" interval = 30 timeout = 5 healthy_threshold = 2 unhealthy_threshold = 2 } tags = { Name = "main-target-group" } } locals { default_user_data = <<-EOT #!/bin/bash set -euo pipefail cat > /opt/devansh-backend.py <<'PY' from http.server import BaseHTTPRequestHandler, HTTPServer import json class Handler(BaseHTTPRequestHandler): def _send_json(self, code, payload): body = json.dumps(payload).encode("utf-8") self.send_response(code) self.send_header("Content-Type", "application/json") self.send_header("Content-Length", str(len(body))) self.end_headers() self.wfile.write(body) def log_message(self, fmt, *args): return def do_GET(self): if self.path == "/labs/health": self._send_json(200, {"status": "OK"}) return if self.path.startswith("/labs/"): lab_id = self.path.split("/labs/", 1)[1] or "unknown" self._send_json(200, {"labId": lab_id, "message": f"Details for lab {lab_id}"}) return self._send_json(404, {"message": "Not found"}) def do_POST(self): if self.path.startswith("/auth/"): self._send_json(200, {"message": "Auth endpoint reachable"}) return self._send_json(404, {"message": "Not found"}) HTTPServer(("", 80), Handler).serve_forever() PY cat > /etc/systemd/system/devansh-backend.service <<'SERVICE' [Unit] Description=Devansh Backend Service After=network.target [Service] Type=simple ExecStart=/usr/bin/python3 /opt/devansh-backend.py Restart=always RestartSec=2 [Install] WantedBy=multi-user.target SERVICE systemctl daemon-reload systemctl enable devansh-backend.service systemctl restart devansh-backend.service EOT } resource "aws_launch_template" "app" { name_prefix = "app-launch-template-" image_id = var.ami_id instance_type = var.instance_type key_name = var.key_name != "" ? var.key_name : null vpc_security_group_ids = [aws_security_group.app_sg.id] user_data = base64encode(var.user_data != "" ? var.user_data : local.default_user_data) metadata_options { http_endpoint = "enabled" http_tokens = "required" } tag_specifications { resource_type = "instance" tags = { Name = "app-instance" } } } resource "aws_autoscaling_group" "app" { min_size = var.min_size max_size = var.max_size desired_capacity = var.desired_capacity vpc_zone_identifier = var.private_subnets target_group_arns = [aws_lb_target_group.main.arn] health_check_type = "ELB" launch_template { id = aws_launch_template.app.id version = "$Latest" } instance_refresh { strategy = "Rolling" preferences { min_healthy_percentage = 50 instance_warmup = 30 } triggers = ["launch_template"] } tag { key = "Name" value = "app-instance" propagate_at_launch = true } } resource "aws_security_group" "alb_sg" { name = "alb-sg" description = "Allow HTTP and HTTPS traffic" 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"] } } resource "aws_security_group" "app_sg" { name = "app-sg" description = "Allow traffic from ALB" vpc_id = var.vpc_id ingress { from_port = 80 to_port = 80 protocol = "tcp" security_groups = [aws_security_group.alb_sg.id] } egress { from_port = 0 to_port = 0 protocol = "-1" cidr_blocks = ["0.0.0.0/0"] } }