删除早于月份的AWS EC2快照

问题描述 投票:2回答:2

下面给出的命令是否可用于删除早于月份的AWS EC2快照。

aws describe-snapshots | grep -v(日期+%Y-%m - )| grep snap- | awk'{print $ 2}'| xargs -n 1 -t aws delete-snapshot

amazon-web-services amazon-ec2
2个回答
10
投票

你的命令不会起作用,主要是因为一个错字:aws describe-snapshots应该是aws ec2 describe-snapshots

无论如何,您可以在没有任何其他工具的情况下执行此操作:

snapshots_to_delete=$(aws ec2 describe-snapshots --owner-ids xxxxxxxxxxxx --query 'Snapshots[?StartTime<=`2017-02-15`].SnapshotId' --output text)
echo "List of snapshots to delete: $snapshots_to_delete"

# actual deletion
for snap in $snapshots_to_delete; do
  aws ec2 delete-snapshot --snapshot-id $snap
done

确保你总是知道你删除了什么。以echo $snap为例。 此外,将--dry-run添加到aws ec2 delete-snapshot可以向您显示请求中没有错误。


编辑:

第一个命令有两点需要注意:

  1. --owner-ids - 您的帐户唯一ID。可以在AWS Console的右上角轻松找到:Support->Support Center->Account Number xxxxxxxxxxxx
  2. --query - 仅获取在指定日期之后创建的快照的JMESPath查询(例如:2017-02-15):Snapshots[?StartTime>=`2017-02-15`].SnapshotId

3
投票

+1来@ roman-zhuzha让我靠近。当$snapshots_to_delete没有解析成由空格分隔的长串快照时,我确实遇到了麻烦。

下面的这个脚本会将它们解析成一串长的快照ID,这些快照ID由我的Ubuntu(可靠)14.04上的空格分隔,其中包含awscli 1.16:

#!/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 \

以下是您可以在哪里找到该号码的示例:

enter image description here


如果在cron中运行它,您只想查看错误和警告。经常出现的警告是有快照正在使用中。两个示例快照ID(snap-a1234xyz,snap-c1234abc)将被忽略,因为否则它们将打印如下内容:

调用DeleteSnapshot操作时发生错误(InvalidSnapshot.InUse):ami-zyx4321ab正在使用快照snap-a1234xyz

有关如何处理此输出,请参阅“snap-a1234xyx”示例快照ID附近的注释。


And don't forget to check on the handy examples and references in the 1.16 aws cli describe-snapshots manual

© www.soinside.com 2019 - 2024. All rights reserved.