Azure DevOps YAML流水线:保留N、N-1、N-2版本Podman镜像清理需求
技术实现建议:Azure DevOps YAML流水线中Podman旧镜像清理任务
核心思路
先筛选出符合imageVx.x.x格式的镜像,提取版本号并按语义化规则降序排序,排除排名前3的最新版本(N、N-1、N-2)后,批量删除剩余的旧镜像。
具体实现步骤
1. 在YAML流水线中添加脚本任务
建议把清理任务放在部署阶段完成后,或者单独设置一个维护阶段,避免影响正在部署的镜像。
2. 筛选并排序镜像版本
通过命令组合提取目标镜像的版本号并排序:
# 过滤出imageV开头的镜像,提取版本号后按语义化降序排序 podman images --format "{{.Repository}}" | grep "^imageV" | sed 's/imageV//' | sort -Vr > image_versions.txt
podman images --format "{{.Repository}}":仅输出镜像仓库名grep "^imageV":精准筛选命名符合要求的镜像sed 's/imageV//':去掉前缀,得到纯版本号(如1.2.3)sort -Vr:按语义化版本降序排列,最新版本排在最前
3. 标记需要保留的版本
从排序结果中取前3个版本,作为需要保留的对象:
# 将前3个版本存入数组 mapfile -t keep_versions < <(head -n 3 image_versions.txt)
4. 生成待删除镜像列表
对比所有版本,把不在保留列表中的镜像标记出来:
# 遍历所有版本,筛选出待删除的镜像 > delete_images.txt for version in $(cat image_versions.txt); do if ! [[ " ${keep_versions[*]} " =~ " ${version} " ]]; then echo "imageV${version}" >> delete_images.txt fi done
5. 执行删除操作
循环删除标记的旧镜像,可根据需求添加--force强制删除关联的运行中容器:
# 批量删除旧镜像 if [ -s delete_images.txt ]; then for image in $(cat delete_images.txt); do echo "正在删除镜像: ${image}" podman rmi --force "${image}" || echo "镜像${image}不存在或删除失败" done else echo "没有需要清理的旧镜像" fi
6. 完整YAML任务示例
stages: - stage: MaintainImages displayName: 维护Podman镜像 jobs: - job: CleanOldImages displayName: 清理旧镜像 steps: - script: | # 筛选并排序镜像版本 podman images --format "{{.Repository}}" | grep "^imageV" | sed 's/imageV//' | sort -Vr > image_versions.txt # 获取需保留的前3个版本 mapfile -t keep_versions < <(head -n 3 image_versions.txt) # 生成待删除镜像列表 > delete_images.txt for version in $(cat image_versions.txt); do if ! [[ " ${keep_versions[*]} " =~ " ${version} " ]]; then echo "imageV${version}" >> delete_images.txt fi done # 删除旧镜像 if [ -s delete_images.txt ]; then for image in $(cat delete_images.txt); do echo "正在删除镜像: ${image}" podman rmi --force "${image}" || echo "镜像${image}删除失败" done else echo "没有需要删除的旧镜像" fi # 清理临时文件 rm -f image_versions.txt delete_images.txt displayName: 执行Podman镜像清理 workingDirectory: $(System.DefaultWorkingDirectory)
注意事项
- 权限配置:确保Azure DevOps代理拥有Podman的操作权限,能正常执行
podman images和podman rmi命令。 - 容器关联处理:如果旧镜像绑定了运行中的容器,
--force会强制删除容器和镜像;若需保留容器,可移除--force参数(此时无法删除关联容器的镜像)。 - 版本匹配精度:如果镜像命名有变体(如带环境后缀),需调整
grep规则,比如用grep "^imageV[0-9]\.[0-9]\.[0-9]$"严格匹配三段式版本。 - 预验证:正式运行前,可把
podman rmi替换成echo,先确认待删除的镜像列表是否正确。
内容的提问来源于stack exchange,提问作者Julie
相关产品推荐
相关产品推荐

