Scheduled Autoscaling with ECS¶
Introduction¶
In order to save costs services should implement scheduled autoscaling on ECS tasks to turn them off during non working hours. This pattern outlines the process for implementing it.
Procedure¶
To add scheduled autoscaling to your ecs tasks, follow these steps:
Scheduled on¶
Remember this should only be set on non-prod environments.
- In your app-deploy folder open your variables.tf file and ensure you have the following variables. The default values should be changed to what is required for your service:
variable "scheduled_auto_scaling" {
default = false
}
variable "ecs_max_count" {
default = 2
}
variable "ecs_desired_count" {
default = 2
}
- Create a new file called autoscaling.tf (or update an existing one if you already have one) and add the following:
/* AUTOSCALING TARGET */
resource "aws_appautoscaling_target" "ecs_as_target" {
max_capacity = var.ecs_max_count
min_capacity = var.ecs_desired_count
resource_id = "service/${data.aws_ecs_cluster.ecs_cluster.cluster_name}/${aws_ecs_service.front_ecs_svc.name}"
scalable_dimension = "ecs:service:DesiredCount"
service_namespace = "ecs"
}
You will need to update the variables in the resource_id above to match the configuration in your setup.
/* AUTOSCALING SCHEDULED ON */
resource "aws_appautoscaling_scheduled_action" "on" {
count = var.scheduled_auto_scaling ? 1 : 0
name = "service-on"
service_namespace = "ecs"
resource_id = aws_appautoscaling_target.ecs_as_target.resource_id
scalable_dimension = "ecs:service:DesiredCount"
schedule = "cron(0 7 * * ? *)"
timezone = "Europe/London"
scalable_target_action {
min_capacity = var.ecs_desired_count
max_capacity = var.ecs_max_count
}
}
- Ensure your dev.tfvars, tst.tfvars and stg.tfvars files have the following entry:
- Ensure your pro.tfvars file has:
Scheduled off¶
- Add the following to your autoscaling.tf file:
/* AUTOSCALING SCHEDULED OFF */
resource "aws_appautoscaling_scheduled_action" "off" {
count = var.scheduled_auto_scaling ? 1 : 0
name = "service-off"
service_namespace = "ecs"
resource_id = aws_appautoscaling_target.ecs_as_target.resource_id
scalable_dimension = "ecs:service:DesiredCount"
schedule = "cron(0 19 * * ? *)"
timezone = "Europe/London"
scalable_target_action {
min_capacity = var.ecs_desired_count
max_capacity = var.ecs_max_count
}
}
Applying¶
- Run your full pipeline for the service component and your autoscaling will be deployed.