Create a snippet of Terraform HCL code that create an AWS autoscaling group, and an ALB…
- User
Create a snippet of Terraform HCL code that create an AWS autoscaling group, and an ALB in front to expose an application to internet.
- Assistant
Here's an example of Terraform HCL code that creates an AWS Autoscaling Group with a Launch Configuration, and an Application Load Balancer (ALB) to expose an application to the internet:
provider "aws" { region = "us-west-2" } resource "aws_launch_configuration" "example" { name_prefix = "example-lc" image_id = "ami-0c55b159cbfafe1f0" instance_type = "t2.micro" user_data = <<-EOF #!/bin/bash echo "Hello, World" > index.html nohup busybox httpd -f -p 80 & EOF } resource "aws_autoscaling_group" "example" { name = "example-asg" launch_configuration = aws_launch_configuration.example.id min_size = 1 max_size = 3 desired_capacity = 2 tag { key = "Name" value = "example-asg" propagate_at_launch = true } } resource "aws_lb" "example" { name = "example-lb" internal = false load_balancer_type = "application" subnets = ["subnet-0e6ba8e39d47d1b61", "subnet-054fa8c06be95d9ed"] security_groups = [aws_security_group.lb_sg.id] tags = { Name = "example-lb" } } resource "aws_security_group" "lb_sg" { name_prefix = "example-lb-sg" ingress { from_port = 80 to_port = 80 protocol = "tcp" cidr_blocks = ["0.0.0.0/0"] } } resource "aws_lb_listener" "http" { load_balancer_arn = aws_lb.example.arn port = 80 protocol = "HTTP" default_action { type = "forward" target_group_arn = aws_lb_target_group.example.arn } } resource "aws_lb_target_group" "example" { name_prefix = "example-tg" port = 80 protocol = "HTTP" vpc_id = "vpc-12345678" target_type = "instance" health_check { path = "/" } } resource "aws_autoscaling_attachment" "example" { autoscaling_group_name = aws_autoscaling_group.example.name alb_target_group_arn = aws_lb_target_group.example.arn }This code creates an Autoscaling Group with a Launch Configuration that creates EC2 instances with an Apache server running a simple "Hello, World" web page on port 80. The Autoscaling Group has a minimum of 1 instance, a maximum of 3 instances, and a desired capacity of 2 instances.
An Application Load Balancer is created and attached to the Autoscaling Group. The ALB listens on port 80 and forwards traffic to the instances using a Target Group that performs a health check on the "/" path. The security group for the ALB is created to allow incoming traffic on port 80 from any IP address.
You can modify the values of the resources to fit your needs, such as changing the region, image ID, instance type, subnets, and VPC ID.