The goal of this task is to implement a highly available and scalable architecture in AWS using Auto Scaling Group (ASG) and an Elastic Load Balancer (ELB). Terraform will be used to provision the infrastructure.
terraform-project/ │── modules/ │ ├── vpc/ │ ├── security-groups/ │ ├── alb/ │ ├── asg/ │── main.tf │── variables.tf │── outputs.tf │── terraform.tfvars │── providers.tf
(modules/vpc/main.tf)
module "vpc" { source = "terraform-aws-modules/vpc/aws" version = "3.11.0" name = "auto-scaling-vpc" cidr = "10.0.0.0/16" azs = ["us-east-1a", "us-east-1b"] public_subnets = ["10.0.1.0/24", "10.0.2.0/24"] enable_dns_hostnames = true enable_dns_support = true }
(modules/security-groups/main.tf)
resource "aws_security_group" "elb_sg" { name = "elb-security-group" description = "Allow HTTP and HTTPS traffic" vpc_id = module.vpc.vpc_id 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"] } }
(modules/alb/main.tf)
module "alb" { source = "terraform-aws-modules/alb/aws" version = "7.1.0" name = "autoscaling-alb" load_balancer_type = "application" vpc_id = module.vpc.vpc_id subnets = module.vpc.public_subnets security_groups = [aws_security_group.elb_sg.id] target_groups = [ { name = "asg-target-group" port = 80 protocol = "HTTP" vpc_id = module.vpc.vpc_id } ] }
(modules/asg/main.tf)
module "asg" { source = "terraform-aws-modules/autoscaling/aws" name = "web-asg" min_size = 2 max_size = 5 desired_capacity = 2 vpc_zone_identifier = module.vpc.public_subnets launch_template = { id = aws_launch_template.web.id version = "$Latest" } target_group_arns = module.alb.target_group_arns }
(modules/asg/launch-template.tf)
resource "aws_launch_template" "web" { name = "web-launch-template" image_id = "ami-0c55b159cbfafe1f0" # Replace with your region-specific AMI ID instance_type = "t2.micro" network_interfaces { associate_public_ip_address = true security_groups = [aws_security_group.elb_sg.id] } user_data = base64encode(<<-EOF #!/bin/bash sudo apt update -y sudo apt install -y apache2 echo "Hello, Terraform!" > /var/www/html/index.html sudo systemctl start apache2 sudo systemctl enable apache2 EOF ) }
output "alb_dns_name" { description = "Load Balancer DNS Name" value = module.alb.lb_dns_name }
terraform init
terraform plan
terraform apply -auto-approve
If you want to destroy the infrastructure:
terraform destroy -auto-approve
This project successfully provisions a highly available and scalable infrastructure using Terraform modules. The Auto Scaling Group (ASG) ensures resilience, while the Elastic Load Balancer (ELB) distributes traffic efficiently.