create AWS application load balancer using terraform
To create an Application Load Balancer using Terraform, you will need to use the aws_alb
resource. Here is an example of how you can create an Application Load Balancer using Terraform:
resource "aws_alb" "sample" {
name = "sample-alb"
internal = false
security_groups = [aws_security_group.alb.id]
subnets = aws_subnet.alb_subnets.*.id
idle_timeout = 60
enable_deletion_protection = false
tags = {
Name = "sample-alb"
}
}
This will create an Application Load Balancer with the specified name, security groups, and subnets. You can then add listeners and target groups to the load balancer using the aws_alb_listener
and aws_alb_target_group
resources.
Here is an example of how you can create a listener and target group for the load balancer:
resource "aws_alb_listener" "sample" {
load_balancer_arn = aws_alb.sample.arn
port = 80
protocol = "HTTP"
default_action {
type = "forward"
target_group_arn = aws_alb_target_group.sample.arn
}
}
resource "aws_alb_target_group" "sample" {
name = "sample-target-group"
port = 80
protocol = "HTTP"
health_check {
path = "/health"
interval = 30
timeout = 5
healthy_threshold = 2
unhealthy_threshold = 2
}
}
This will create a listener on port 80 that forwards traffic to the target group on port 80. The target group will have a health check configured to check the /health
endpoint on the targets with a 30 second interval and a 5 second timeout.