terraform { required_version = ">= 1.0.0, < 2.0.0" required_providers { aws = { source = "hashicorp/aws" version = "~> 4.0" } } } provider "aws" { profile = "superuser" region = "ap-southeast-2" } data "aws_ami" "aws_linux_ami" { most_recent = true owners = ["amazon"] filter { name = "name" values = ["al*-ami-*-x86_64*"] } } data "aws_vpc" "default" { default = true } data "aws_subnets" "default" { filter { name = "vpc-id" values = [data.aws_vpc.default.id] } } resource "aws_launch_configuration" "server_ami" { image_id = data.aws_ami.aws_linux_ami.id instance_type = "t2.micro" security_groups = [ aws_security_group.server-sg.id ] key_name = "debin" user_data = <<-EOF #!/bin/bash su - sudo yum update -y sudo yum install -y httpd.x86_64 echo "Hello, World " > /var/www/html/index.html sudo systemctl start httpd.service sudo systemctl enable httpd.service EOF lifecycle { create_before_destroy = true } } resource "aws_autoscaling_group" "server_group" { min_size = 2 max_size = 10 launch_configuration = aws_launch_configuration.server_ami.name vpc_zone_identifier = data.aws_subnets.default.ids target_group_arns = [aws_lb_target_group.target_group.arn] health_check_type = "ELB" tag { key = "Name" value = "ASEC2" propagate_at_launch = true } } resource "aws_security_group" "server-sg" { name = "alb_sec_group" ingress { description = "TLS from VPC" from_port = var.server_port to_port = var.server_port protocol = "tcp" cidr_blocks = ["0.0.0.0/0"] ipv6_cidr_blocks = ["::/0"] } egress { description = "all" from_port = 0 to_port = 0 protocol = "-1" cidr_blocks = ["0.0.0.0/0"] ipv6_cidr_blocks = ["::/0"] } } resource "aws_lb" "load_balancer" { name = "dummy-server-lb" load_balancer_type = "application" subnets = data.aws_subnets.default.ids security_groups = [aws_security_group.alb_sg.id] } resource "aws_alb_listener" "http_endpoint" { load_balancer_arn = aws_lb.load_balancer.arn port = 80 protocol = "HTTP" default_action { type = "fixed-response" fixed_response { content_type = "text/plain" message_body = "404" status_code = 404 } } } resource "aws_security_group" "alb_sg" { name = "autogerenated-exmaple-alb" ingress { from_port = 80 to_port = 80 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_lb_target_group" "target_group" { name = "aws-target-group" port = var.server_port protocol = "HTTP" vpc_id = data.aws_vpc.default.id health_check { path = "/" protocol = "HTTP" matcher = "200" interval = 15 timeout = 3 healthy_threshold = 2 unhealthy_threshold = 2 } } resource "aws_lb_listener_rule" "expose_80" { listener_arn = aws_alb_listener.http_endpoint.arn priority = 100 condition { path_pattern { values = ["*"] } } action { type = "forward" target_group_arn = aws_lb_target_group.target_group.arn } }