Skip to content

Instantly share code, notes, and snippets.

@amanjeev
Created October 7, 2018 04:24
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save amanjeev/7ad52fed4a1ee2d38ebf08023d943e53 to your computer and use it in GitHub Desktop.
Save amanjeev/7ad52fed4a1ee2d38ebf08023d943e53 to your computer and use it in GitHub Desktop.
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