如何使用Serverless为已有ECR仓库附加生命周期策略?
为Serverless部署的ECR仓库添加生命周期策略解决镜像存储占用问题
当前Serverless框架的ECR配置仅能创建仓库,无法直接定义生命周期策略,多次部署生成的镜像会持续占用存储资源。以下是两种可行的解决方案:
方案一:通过Serverless自定义CloudFormation资源自动配置
保持原有ECR部署配置不变,在serverless.yml中添加resources字段,定义ECR生命周期策略资源并关联到自动创建的仓库:
# 原有ECR配置 ecr: { images: { appImage: { path: ".", }, }, }, # 添加自定义资源 resources: Resources: ECRLifecyclePolicy: Type: AWS::ECR::LifecyclePolicy Properties: RepositoryName: !Ref AppImageECRRepository # 引用Serverless自动创建的ECR仓库资源 LifecyclePolicyText: Version: '2021-09-01' Rules: - RulePriority: 1 Description: "保留最近3个镜像,清理旧镜像" Selection: TagStatus: ANY CountType: IMAGE_COUNT_MORE_THAN CountNumber: 3 Action: Type: EXPIRE
- 注意:
AppImageECRRepository是Serverless自动生成的ECR仓库资源逻辑ID,格式通常为[服务名]-[部署环境]-appImage-ECRRepository,若不确定可通过aws cloudformation describe-stack-resources --stack-name <你的栈名>命令查询。 - 可根据需求调整策略规则,比如仅清理无标签镜像:
LifecyclePolicyText: Version: '2021-09-01' Rules: - RulePriority: 1 Description: "清理所有无标签镜像" Selection: TagStatus: UNTAGGED CountType: ANY Action: Type: EXPIRE
部署时Serverless会自动将该策略附加到ECR仓库,后续镜像会按规则自动清理。
方案二:使用AWS CLI手动添加策略
若已创建ECR仓库,可直接通过CLI命令添加生命周期策略:
- 创建
lifecycle-policy.json文件,内容示例:
{ "version": "2021-09-01", "rules": [ { "rulePriority": 1, "description": "保留最近5个镜像", "selection": { "tagStatus": "ANY", "countType": "IMAGE_COUNT_MORE_THAN", "countNumber": 5 }, "action": { "type": "EXPIRE" } } ] }
- 执行CLI命令:
aws ecr put-lifecycle-policy --repository-name <你的ECR仓库名> --lifecycle-policy-text file://lifecycle-policy.json
内容的提问来源于stack exchange,提问作者Aryan
相关产品推荐
相关产品推荐

