AWS ECS 服务任务回收

发布: (2026年1月2日 GMT+8 16:13)
7 分钟阅读
原文: Dev.to

I’m happy to translate the article for you, but I’ll need the full text of the post (the paragraphs, headings, etc.) in order to do so. Could you please paste the content you’d like translated? I’ll keep the source line, markdown formatting, code blocks, URLs, and technical terms exactly as they are while translating the surrounding text into Simplified Chinese.

概览

  • 将任务逐个停止,而不是并行替换
  • 在每次任务替换之间等待服务稳定
  • 可选地通过临时增加容量来保持服务状态
  • 可配置的任务替换间等待时间

Features

  • Sequential Task Recycling – 逐个停止并替换任务
  • Service Stability – 在每次任务替换后等待系统达到稳定状态
  • Capacity Management – 可选的临时容量提升,以保持可用性
  • Autoscaling Support – 支持使用 Application Auto Scaling 的服务
  • Flexible Authentication – 通过 AWSSession 模块提供多种 AWS 凭证方式
  • Email Notifications – 完成后可选的 SMTP 邮件通知
  • CloudFormation Deployment – 基础设施即代码,自动化部署
  • Zero RetriesEventInvokeConfig 设置为 0 次重试
  • Comprehensive Logging – 详细的 CloudWatch 日志用于监控

架构

Lambda Function (Python 3.13)
├── Event-driven execution
├── AWSSession.py (AWS authentication)
├── Notification.py (Email notifications)
└── input.json (Configuration)

前置条件

  • Python 3.13+
  • 已配置 AWS CLI
  • 对 ECS 和 Application Auto Scaling 的 IAM 权限
  • SMTP 服务器(可选,用于通知)

安装

1. 克隆仓库

cd aws-ecs-service-task-recycle

2. 配置设置

使用您的配置编辑 input.json

{
  "awsCredentials": {
    "region_name": "us-east-1"
  },
  "smtpCredentials": {
    "host": "smtp.example.com",
    "port": "587",
    "username": "user@example.com",
    "password": "password",
    "from_email": "noreply@example.com"
  },
  "emailNotification": {
    "email_subject": "ECS Service Task Recycle Completed",
    "subject_prefix": "AWS ECS",
    "to": ["admin@example.com"]
  }
}

3. 部署 CloudFormation 堆栈

chmod +x cloudformation_deploy.sh lambda_build.sh
./cloudformation_deploy.sh

用法

Lambda 事件参数

{
  "cluster_name": "my-ecs-cluster",
  "service_name": "my-service",
  "maintain_service_state": true,
  "wait_time": 30
}

参数

参数必需默认描述
cluster_nameECS 集群名称
service_nameECS 服务名称
maintain_service_statetrue临时将容量增加 1
wait_time30任务替换之间的等待秒数

调用 Lambda 函数

AWS CLI

aws lambda invoke \
  --function-name ecs-task-recycle-function \
  --payload '{"cluster_name":"my-cluster","service_name":"my-service","maintain_service_state":true,"wait_time":30}' \
  response.json

AWS Console

  1. 前往 Lambda → Functions → ecs-task-recycle-function
  2. 打开 Test 选项卡 → Create test event
  3. 添加事件 JSON 并点击 Test

工作原理

流程

  1. 获取当前状态 – 检索服务配置和运行中的任务
  2. 增加容量(如果 maintain_service_state=true) – 将期望计数加 1
  3. 等待稳定 – 确保新任务已运行
  4. 回收任务 – 对每个旧任务:
    • 停止任务
    • 等待替代任务启动
    • 等待服务稳定
    • 按配置的 wait_time 休眠
  5. 恢复容量 – 返回原始的期望计数
  6. 发送通知 – 电子邮件报告(如果已配置)

示例场景

拥有 3 个任务的服务

Initial State: 3 tasks running

Increase to 4 tasks (maintain availability)

Stop task 1 → Wait stable → Sleep 30s

Stop task 2 → Wait stable → Sleep 30s

Stop task 3 → Wait stable → Sleep 30s

Restore to 3 tasks

Complete

配置

AWS 凭证 (input.json)

支持多种身份验证方法:

{
  "awsCredentials": {
    "region_name": "us-east-1",
    "profile_name": "my-profile",
    "role_arn": "arn:aws:iam::123456789012:role/MyRole",
    "access_key": "AKIAIOSFODNN7EXAMPLE",
    "secret_key": "wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY",
    "session_token": "token"
  }
}

SMTP 配置(可选)

{
  "smtpCredentials": {
    "host": "smtp.gmail.com",
    "port": "587",
    "username": "user@gmail.com",
    "password": "app-password",
    "from_email": "noreply@example.com"
  }
}

IAM 权限

所需权限(已包含在 CloudFormation 模板中):

{
  "Effect": "Allow",
  "Action": [
    "ecs:DescribeServices",
    "ecs:UpdateService",
    "ecs:ListTasks",
    "ecs:StopTask",
    "ecs:DescribeTasks",
    "application-autoscaling:DescribeScalableTargets",
    "application-autoscaling:RegisterScalableTarget"
  ],
  "Resource": "*"
}

CloudFormation Resources

  • Lambda Function: Python 3.13 运行时,900 秒 超时,256 MB 内存
  • IAM Role: 具有 ECS 和 Auto Scaling 权限的执行角色
  • EventInvokeConfig: MaximumRetryAttempts 设置为 0
  • CloudWatch Logs: 7 天 保留

监控

CloudWatch 日志

aws logs tail /aws/lambda/ecs-task-recycle-function --follow

关键日志信息

  • Starting task recycle for {cluster}/{service}
  • Original desired count: X, tasks: Y
  • Recycling task N/M: {task_arn}
  • Task N recycled, waiting Xs
  • Task recycle completed successfully

故障排除

服务未稳定

  • 在代码中增加 waiter MaxAttempts(默认: 40)
  • 检查 ECS 服务健康和任务定义
  • 验证目标组健康检查

超时错误

  • 增加 Lambda 超时时间(默认: 900 s)
  • 减少任务数量或增加 wait_time

认证失败

  • 验证 IAM 角色权限
  • 检查 input.json 中的 AWS 凭证
  • 确保 Lambda 执行角色正确

Best Practices

  • 在非生产环境测试 – 首先在非关键服务上进行测试。
  • 监控 CloudWatch – 在首次执行时查看日志。
  • 调整等待时间 – 根据应用启动时间进行调优。
  • 使用保持状态 – 为生产服务启用此功能。
  • 合理安排调度 – 在低流量时段运行。

Comparison with Force Deployment

功能Force DeploymentTask Recycle
任务替换并行顺序
服务中断更高更低
完成时间更快更慢
控制有限可配置
任务间等待

安全考虑

  • Lambda 执行角色遵循最小权限原则。
  • 代码中没有硬编码凭证。
  • SMTP 凭证存储在 input.json 中(生产环境请使用 Secrets Manager)。
  • CloudWatch 日志提供审计追踪。
  • EventInvokeConfig 防止重试风暴。

成本优化

  • Lambda 执行时间 ≈ (任务数 × 等待时间)秒。
  • CloudWatch 日志:7 天保留(无额外存储费用)。
  • 无额外的 AWS 服务费用。
  • 考虑在非高峰时段调度,以降低间接成本。

Limitations

  • 最大 Lambda 执行时间:15 分钟
  • 适用于 < 20 个任务 的服务(等待时间为 30 秒)。
  • 需要一个稳定的服务才能使等待者成功。
  • 失败时没有自动回滚机制。

贡献

欢迎贡献!请遵循仓库结构:

  1. 彻底测试更改。
  2. 更新文档。
  3. 遵循现有代码风格。
  4. 添加适当的错误处理。
Back to Blog

相关文章

阅读更多 »

RGB LED 支线任务 💡

markdown !Jennifer Davishttps://media2.dev.to/dynamic/image/width=50,height=50,fit=cover,gravity=auto,format=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%...

Mendex:我为何构建

介绍 大家好。今天我想分享一下我是谁、我在构建什么以及为什么。 早期职业生涯与倦怠 我在 17 年前开始我的 developer 生涯……