### ECS AutoScaling Alarmresource "aws_cloudwatch_metric_alarm" "nginx_service_high" { alarm_name = "nginx-service-CPU-Utilization-High-30" comparison_operator = "GreaterThanOrEqualToThreshold" evaluation_periods = "1" metric_name = "CPUUtilization" namespace = "AWS/ECS" period = "60" statistic = "Average" threshold = "30"
dimensions { ClusterName = "${aws_ecs_cluster.main.name}" ServiceName = "${aws_ecs_service.nginx.name}" }
alarm_actions = ["${aws_appautoscaling_policy.nginx_up.arn}"]}
resource "aws_cloudwatch_metric_alarm" "nginx_service_low" { alarm_name = "nginx-service-CPU-Utilization-Low-5" comparison_operator = "LessThanThreshold" evaluation_periods = "1" metric_name = "CPUUtilization" namespace = "AWS/ECS" period = "60" statistic = "Average" threshold = "5"
dimensions { ClusterName = "${aws_ecs_cluster.main.name}" ServiceName = "${aws_ecs_service.nginx.name}" }
alarm_actions = ["${aws_appautoscaling_policy.nginx_down.arn}"]}
resource "aws_appautoscaling_target" "nginx_scale_target" { service_namespace = "ecs" resource_id = "service/${aws_ecs_cluster.main.name}/${aws_ecs_service.nginx.name}" scalable_dimension = "ecs:service:DesiredCount" role_arn = "${aws_iam_role.ecs_autoscale_role.arn}" min_capacity = 1 max_capacity = 4
depends_on = [ "aws_ecs_cluster.main", "aws_ecs_service.nginx" ]
}
resource "aws_appautoscaling_policy" "nginx_up" { name = "nginx-scale-up" service_namespace = "ecs" resource_id = "service/${var.ecs_cluster_name}/${aws_ecs_service.nginx.name}" scalable_dimension = "ecs:service:DesiredCount"
adjustment_type = "ChangeInCapacity" cooldown = 300 metric_aggregation_type = "Average"
step_adjustment { metric_interval_lower_bound = 0 scaling_adjustment = 1 } depends_on = [ "aws_appautoscaling_target.nginx_scale_target" ]}
resource "aws_appautoscaling_policy" "nginx_down" { name = "nginx-scale-down" service_namespace = "ecs" resource_id = "service/${var.ecs_cluster_name}/${aws_ecs_service.nginx.name}" scalable_dimension = "ecs:service:DesiredCount"
adjustment_type = "ChangeInCapacity" cooldown = 300 metric_aggregation_type = "Average"
step_adjustment { metric_interval_lower_bound = 0 scaling_adjustment = -1 } depends_on = [ "aws_appautoscaling_target.nginx_scale_target" ]}
resource "aws_iam_role" "ecs_autoscale_role" { name = "ecsAutoscaleRole" assume_role_policy = "${file("${path.module}/autoscale-assume-role.json")}"}
resource "aws_iam_policy_attachment" "ecs_autoscale_role_attach" { name = "ecs-autoscale-role-attach" roles = ["${aws_iam_role.ecs_autoscale_role.name}"] policy_arn = "arn:aws:iam::aws:policy/service-role/AmazonEC2ContainerServiceAutoscaleRole"}{ "Version": "2012-10-17", "Statement": [ { "Effect": "Allow", "Principal": { "Service": "application-autoscaling.amazonaws.com" }, "Action": "sts:AssumeRole" } ]}