Terraformでターゲット追跡スケーリングポリシーのAuto Scalingを実装する
AWSメモ記事でゲス。
AWSのECSにおけるオートスケールは、EC2インスタンスのオートスケールと、インスタンス内のコンテナのオートスケールのコンテキストがありますが、
これはFARGATEでの運用を考えて書いたものなのでコンテナをターゲットにしています。参考:Service Auto Scaling
locals { cluster_name = "my-server" service_name = "my-server" // service/cluster-name/service-name resource_id = "service/my-server/my-server" } # autoscaleするターゲットを決める # https://www.terraform.io/docs/providers/aws/r/appautoscaling_target.html#ecs-service-autoscaling resource "aws_appautoscaling_target" "my_server_target" { service_namespace = "ecs" resource_id = local.resource_id scalable_dimension = "ecs:service:DesiredCount" role_arn = data.aws_iam_role.ecs_service_autoscaling.arn min_capacity = 1 max_capacity = 5 # 変更はGUIのほうがやりやすそうなので lifecycle { ignore_changes = [min_capacity, max_capacity] } } # https://www.terraform.io/docs/providers/aws/r/appautoscaling_policy.html#ecs-service-autoscaling # https://docs.aws.amazon.com/ja_jp/AmazonECS/latest/developerguide/service-auto-scaling.html resource "aws_appautoscaling_policy" "scale_policy" { name = "my-server-scale-policy" service_namespace = "ecs" resource_id = local.resource_id scalable_dimension = "ecs:service:DesiredCount" policy_type = "TargetTrackingScaling" target_tracking_scaling_policy_configuration { predefined_metric_specification { predefined_metric_type = "ECSServiceAverageCPUUtilization" } # CPU使用率 50 を維持する感じ target_value = 50 scale_out_cooldown = 300 scale_in_cooldown = 300 } depends_on = [aws_appautoscaling_target.my_server_target] } data "aws_iam_role" "ecs_service_autoscaling" { name = "AWSServiceRoleForApplicationAutoScaling_ECSService" }
参考
サービスの Auto Scaling - Amazon Elastic Container Service
AWS: aws_appautoscaling_target - Terraform by HashiCorp
AWS: aws_appautoscaling_policy - Terraform by HashiCorp
AWS Fargate Scaling with Target Tracking Policy - Kiran Gekkula - Medium