You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何彻底关停AWS账号中的一个ECS集群及相关资源?

彻底关停AWS ECS集群的无残留操作指南

批量处理ECS服务(替代手动改任务数)

你有7-8个服务手动改太麻烦,直接用AWS CLI批量把所有服务的期望任务数设为0:

  1. 先拉取目标集群的所有服务ARN:
aws ecs list-services --cluster <你的集群名> --query 'serviceArns' --output text | tr '\t' '\n'
  1. 批量更新服务:
for service in $(aws ecs list-services --cluster <你的集群名> --query 'serviceArns' --output text | tr '\t' '\n'); do
  aws ecs update-service --cluster <你的集群名> --service $service --desired-count 0
done

执行完后,所有服务的任务会逐步停止,不会有残留运行的任务。

处理关联的自动伸缩组(ASG)

把ASG期望计数设为0的行为,取决于实例保护设置:

  • 默认情况下(无实例保护):ASG会直接终止所有EC2实例;
  • 若开启了实例保护:ASG会先尝试停止实例,无法停止时才会终止。
    要确保彻底清理,按以下步骤来:
  1. 关闭ASG内所有实例的实例保护(如果开了):
aws autoscaling set-instance-protection \
  --auto-scaling-group-name <你的ASG名> \
  --instances $(aws autoscaling describe-auto-scaling-groups --auto-scaling-group-names <你的ASG名> --query 'AutoScalingGroups[0].Instances[*].InstanceId' --output text) \
  --no-protected-from-scale-in
  1. 将ASG期望容量设为0:
aws autoscaling update-auto-scaling-group --auto-scaling-group-name <你的ASG名> --desired-capacity 0

这一步会自动终止所有ASG内的EC2实例,不会留下处于停止状态的实例占用资源。

收尾:清理残留资源

为了完全无残留,还要处理这些关联资源:

  • 删除集群内所有不需要的任务定义版本:
for task_def in $(aws ecs list-task-definitions --family-prefix <你的任务定义前缀> --query 'taskDefinitionArns' --output text | tr '\t' '\n'); do
  aws ecs deregister-task-definition --task-definition $task_def
done
  • 解绑并删除仅服务于该集群的负载均衡器、目标组、安全组(如果这些资源不再使用)
  • 最后删除ECS集群本身:
aws ecs delete-cluster --cluster <你的集群名>

对你两种思路的点评

  • 方法1(手动改任务数):可行但效率极低,用上面的CLI批量命令可以1分钟搞定;
  • 方法2(ASG设为0):单独用的话可能因为实例保护留下停止的实例,必须先关闭实例保护才能彻底终止所有EC2。

内容的提问来源于stack exchange,提问作者Maharshi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.06 22:55:29