+1 @roman-zuzha 让我靠近。当$snapshots_to_delete 没有解析成一长串由空格分隔的快照时,我确实遇到了麻烦。
下面的这个脚本确实将它们解析成一长串快照 ID,在我的 Ubuntu(可信)14.04 上使用 awscli 1.16 进行 bash 分隔:
#!/usr/bin/env bash
dry_run=1
echo_progress=1
d=$(date +'%Y-%m-%d' -d '1 month ago')
if [ $echo_progress -eq 1 ]
then
echo "Date of snapshots to delete (if older than): $d"
fi
snapshots_to_delete=$(aws ec2 describe-snapshots \
--owner-ids xxxxxxxxxxxxx \
--output text \
--query "Snapshots[?StartTime<'$d'].SnapshotId" \
)
if [ $echo_progress -eq 1 ]
then
echo "List of snapshots to delete: $snapshots_to_delete"
fi
for oldsnap in $snapshots_to_delete; do
# some $oldsnaps will be in use, so you can't delete them
# for "snap-a1234xyz" currently in use by "ami-zyx4321ab"
# (and others it can't delete) add conditionals like this
if [ "$oldsnap" = "snap-a1234xyz" ] ||
[ "$oldsnap" = "snap-c1234abc" ]
then
if [ $echo_progress -eq 1 ]
then
echo "skipping $oldsnap known to be in use by an ami"
fi
continue
fi
if [ $echo_progress -eq 1 ]
then
echo "deleting $oldsnap"
fi
if [ $dry_run -eq 1 ]
then
# dryrun will not actually delete the snapshots
aws ec2 delete-snapshot --snapshot-id $oldsnap --dry-run
else
aws ec2 delete-snapshot --snapshot-id $oldsnap
fi
done
根据需要切换这些变量:
dry_run=1 # set this to 0 to actually delete
echo_progress=1 # set this to 0 to not echo stmnts
将date -d 字符串更改为您要删除“早于”的天数、月数或年数的人类可读版本:
d=$(date +'%Y-%m-%d' -d '15 days ago') # half a month
找到您的帐户 ID 并将这些 XXXX 更新为该号码:
--owner-ids xxxxxxxxxxxxx \
这是一个可以找到该号码的示例:
如果在 cron 中运行它,您只想看到错误和警告。一个常见的警告是正在使用快照。两个示例快照 id (snap-a1234xyz, snap-c1234abc) 会被忽略,否则它们会打印如下内容:
调用 DeleteSnapshot 操作时发生错误 (InvalidSnapshot.InUse):快照 snap-a1234xyz 当前正在被 ami-zyx4321ab 使用
请参阅“snap-a1234xyx”示例快照 ID 附近的 cmets,了解如何处理此输出。
And don't forget to check on the handy examples and references in the 1.16 aws cli describe-snapshots manual.