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

如何获取GCE镜像家族中可清理的未使用旧镜像排序列表

获取GCE镜像家族的旧镜像排序列表并清理

你说的太对了,gcloud compute images describe-from-family这个命令本来就只返回镜像家族里的最新版本,要拿到所有旧镜像并按时间排序,得用gcloud compute images list搭配过滤和排序参数来实现。

1. 列出指定家族的所有镜像并按创建时间排序

用下面的命令就能得到目标家族的所有镜像,并且按创建时间倒序(最新的在前)排列,输出清晰的表格:

gcloud compute images list --filter="family:test-packerized-centos7-base" --sort-by="~creationTimestamp" --format="table(name, creationTimestamp, status)"

参数解释:

  • --filter="family:XXX":精准筛选属于目标镜像家族的所有镜像
  • --sort-by="~creationTimestamp":~符号表示倒序排序,如果想让最旧的镜像排在前面,去掉~即可
  • --format:指定输出格式为表格,展示镜像名称、创建时间和状态,方便快速查看

如果需要更详细的信息(比如镜像ID、磁盘大小),可以调整表格字段:

gcloud compute images list --filter="family:test-packerized-centos7-base" --sort-by="creationTimestamp" --format="table(name, id, creationTimestamp, diskSizeGb, status)"

2. 导出列表用于批量清理

如果要写脚本批量清理旧镜像,可以把列表导出为JSON或CSV格式:

# 导出为JSON格式
gcloud compute images list --filter="family:test-packerized-centos7-base" --sort-by="creationTimestamp" --format="json" > old_images.json

# 导出为CSV格式(仅保留名称和创建时间)
gcloud compute images list --filter="family:test-packerized-centos7-base" --sort-by="creationTimestamp" --format="csv(name,creationTimestamp)" > old_images.csv

3. 批量清理旧镜像(保留最新版本)

如果想自动删除旧镜像,只保留最新的N个,比如保留最新2个,删除剩下的:

# 按倒序列出镜像名称,跳过前2个最新的,批量删除剩下的
gcloud compute images list --filter="family:test-packerized-centos7-base" --sort-by="~creationTimestamp" --format="value(name)" | tail -n +3 | xargs gcloud compute images delete -q

这里的tail -n +3表示从第3行开始取(也就是跳过前2个最新镜像),-q参数会自动确认删除操作,无需手动输入Y。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.26 10:09:54