Skip to content

Instantly share code, notes, and snippets.

@overnew
Created July 2, 2024 04:35
Show Gist options
  • Save overnew/ff0a812197bdd4f6317907161b4c9c4e to your computer and use it in GitHub Desktop.
Save overnew/ff0a812197bdd4f6317907161b4c9c4e to your computer and use it in GitHub Desktop.
ecs task autoscaling example
resource "aws_ecs_service" "web_service" {
name = local.web_name
cluster = aws_ecs_cluster.web_cluster.id
task_definition = aws_ecs_task_definition.web_task.arn
desired_count = 2
launch_type = "FARGATE"
scheduling_strategy = "REPLICA"
deployment_controller {
type = "CODE_DEPLOY"
}
network_configuration {
subnets = [var.web_subnet_ids[0],var.web_subnet_ids[1]]
assign_public_ip = false
security_groups = [var.web_security_group]
}
load_balancer {
target_group_arn = aws_lb_target_group.web_target_group.arn
container_name = "web"
container_port = 80
}
depends_on = [aws_lb_listener.service_listener]
}
#ecs task auto scaling
resource "aws_appautoscaling_target" "ecs_web_target" {
max_capacity = 10
min_capacity = 1
resource_id = "service/${aws_ecs_cluster.web_cluster.name}/${aws_ecs_service.web_service.name}"
scalable_dimension = "ecs:service:DesiredCount"
service_namespace = "ecs"
}
resource "aws_appautoscaling_policy" "ecs_web_scale_out" {
name = "${local.web_name}-auto-scaling-out"
policy_type = "StepScaling"
resource_id = aws_appautoscaling_target.ecs_web_target.resource_id
scalable_dimension = aws_appautoscaling_target.ecs_web_target.scalable_dimension
service_namespace = aws_appautoscaling_target.ecs_web_target.service_namespace
#StepScaling
step_scaling_policy_configuration {
adjustment_type = "ChangeInCapacity"
#cooldown은 스케일링 후 다음 스케일링까지의 유예 시간
cooldown = 120
#Average가 default
metric_aggregation_type = "Average" #"Maximum"
step_adjustment {
metric_interval_lower_bound = 0
metric_interval_upper_bound = 10
#scaling 개수, 음 or 양
scaling_adjustment = 1
}
step_adjustment {
metric_interval_lower_bound = 10
metric_interval_upper_bound = 20
scaling_adjustment = 2
}
step_adjustment {
metric_interval_lower_bound = 20
scaling_adjustment = 3
}
}
depends_on = [ aws_appautoscaling_target.ecs_web_target ]
}
# scaling out 알람
resource "aws_cloudwatch_metric_alarm" "outscaling_metric_alarm" {
alarm_name = "${local.web_name}-outscaling-metric-alarm"
comparison_operator = "GreaterThanOrEqualToThreshold"
evaluation_periods = "1"
metric_name = "CPUUtilization"
namespace = "AWS/ECS"
period = "30"
statistic = "Average"
threshold = "30" #30에서부터 scaling
dimensions = {
ClusterName = "${aws_ecs_cluster.web_cluster.name}"
ServiceName = "${aws_ecs_service.web_service.name}"
}
#이 알람이 scaling policy을 트리거한다.
alarm_actions = ["${aws_appautoscaling_policy.ecs_web_scale_out.arn}",
var.slack_sns_arn
]
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment