Instantly share code, notes, and snippets.

Embed
What would you like to do?
AWS Auto Scaling Group with Application Load Balancer using Terraform
# Create a basic ALB
resource "aws_alb" "my-app-alb" {
name = "my-app-alb"
}
# Create target groups with one health check per group
resource "aws_alb_target_group" "target-group-1" {
name = "target-group-1"
port = 80
protocol = "HTTP"
lifecycle { create_before_destroy=true }
health_check {
path = "/api/1/resolve/default?path=/service/my-service"
port = 2001
healthy_threshold = 6
unhealthy_threshold = 2
timeout = 2
interval = 5
matcher = "200"
}
}
resource "aws_alb_target_group" "target-group-2" {
name = "target-group-2"
port = 80
protocol = "HTTP"
lifecycle { create_before_destroy=true }
health_check {
path = "/api/2/resolve/default?path=/service/my-service"
port = 2010
healthy_threshold = 6
unhealthy_threshold = 2
timeout = 2
interval = 5
matcher = "200"
}
}
# Create a Listener
resource "aws_alb_listener" "my-alb-listener" {
default_action {
target_group_arn = "${aws_alb_target_group.target-group-1.arn}"
type = "forward"
}
load_balancer_arn = "${aws_alb.my-app-alb.arn}"
port = 80
protocol = "HTTP"
}
# Create Listener Rules
resource "aws_alb_listener_rule" "rule-1" {
action {
target_group_arn = "${aws_alb_target_group.target-group-1.arn}"
type = "forward"
}
condition { field="path-pattern" values=["/api/1/resolve/default"] }
listener_arn = "${aws_alb_listener.my-alb-listener.id}"
priority = 100
}
resource "aws_alb_listener_rule" "rule-2" {
action {
target_group_arn = "${aws_alb_target_group.target-group-2.arn}"
type = "forward"
}
condition { field="path-pattern" values=["/api/2/resolve/default"] }
listener_arn = "${aws_alb_listener.my-alb-listener.id}"
priority = 101
}
# Create an ASG that ties all of this together
resource "aws_autoscaling_group" "my-alb-asg" {
name = "my-alb-asg"
min_size = "3"
max_size = "6"
launch_configuration = "${aws_launch_configuration.my-app-alb.name}"
termination_policies = [
"OldestInstance",
"OldestLaunchConfiguration",
]
health_check_type = "ELB"
depends_on = [
"aws_alb.my-app-alb",
]
target_group_arns = [
"${aws_alb_target_group.target-group-1.arn}",
"${aws_alb_target_group.target-group-2.arn}",
]
lifecycle {
create_before_destroy = true
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment