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

如何通过Boto3实现ECS Fargate任务停止并递减期望任务数?

停止Fargate任务并同步调整自动扩缩容期望数

核心结论

ECS服务的自动扩缩容完全支持调整期望任务数,且Fargate场景下无需依赖EC2实例ID(Fargate无暴露的EC2实例,EC2元数据URI不适用于此场景)。要实现「停止任务且不让自动扩缩容补充新任务」的需求,需先调降服务的期望任务数,再停止目标任务,具体实现步骤如下:


实现步骤(Boto3)

1. 初始化客户端

import boto3

# 初始化ECS和应用自动扩缩容客户端
ecs_client = boto3.client('ecs')
app_asg_client = boto3.client('application-autoscaling')

2. 获取任务所属的ECS服务信息

通过任务ID查询其关联的服务ARN,再解析出集群和服务名称:

def get_task_service_info(cluster_arn, task_id):
    task_details = ecs_client.describe_tasks(cluster=cluster_arn, tasks=[task_id])
    service_arn = task_details['tasks'][0]['serviceArn']
    # 构造应用自动扩缩容所需的资源ID格式
    cluster_name = cluster_arn.split('/')[-1]
    service_name = service_arn.split('/')[-1]
    resource_id = f"service/{cluster_name}/{service_name}"
    return service_name, resource_id

3. 调降服务的期望任务数

先获取当前期望任务数,再通过应用自动扩缩容API将其递减1(确保不低于0):

def decrement_service_desired_count(cluster_arn, service_name, resource_id):
    # 获取当前服务的期望任务数
    service_details = ecs_client.describe_services(cluster=cluster_arn, services=[service_name])
    current_desired = service_details['services'][0]['desiredCount']
    new_desired = max(current_desired - 1, 0)

    # 获取服务对应的可扩缩容目标ARN
    scalable_targets = app_asg_client.describe_scalable_targets(
        ServiceNamespace='ecs',
        ResourceIds=[resource_id],
        ScalableDimension='ecs:service:DesiredCount'
    )
    target_arn = scalable_targets['ScalableTargets'][0]['ScalableTargetARN']

    # 设置新的期望任务数
    app_asg_client.set_desired_capacity(
        ScalableTargetARN=target_arn,
        DesiredCapacity=new_desired,
        HonorCooldown=False  # 若需遵守扩缩容冷却时间,改为True
    )
    return new_desired

4. 停止目标任务

调整完期望数后,调用ECS API停止指定任务:

def stop_target_task(cluster_arn, task_id):
    ecs_client.stop_task(cluster=cluster_arn, task=task_id)

整合调用

def handle_idle_fargate_task(cluster_arn, task_id):
    service_name, resource_id = get_task_service_info(cluster_arn, task_id)
    decrement_service_desired_count(cluster_arn, service_name, resource_id)
    stop_target_task(cluster_arn, task_id)

关键说明

  1. EC2实例ID不适用Fargate:Fargate任务运行在AWS托管的无服务器基础设施上,任务元数据中没有EC2实例ID,EC2的实例元数据URI对Fargate完全无效,无需尝试使用。
  2. 权限要求:执行代码的IAM角色需具备以下权限:
    • ecs:DescribeTasks、ecs:DescribeServices、ecs:StopTask
    • application-autoscaling:DescribeScalableTargets、application-autoscaling:SetDesiredCapacity
  3. 冷却时间控制:HonorCooldown参数设为False可立即调整期望数,若服务配置了扩缩容冷却时间且需遵守,可改为True。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.02 02:45:17