识别和删除12个月前的AWS中的孤立快照

时间:2019-05-30 13:29:22

标签: python bash amazon-web-services snapshot

我的AWS账户中有成千上万个12个月大的快照。因此,必须删除存在12个月的快照。但是这里的挑战是,我必须确定孤立快照(未附加到任何AMI或未由任何AMI创建),然后首先将其删除。

请帮助我添加一个脚本,以识别超过12个月的孤儿快照。

请帮我编写脚本。

#!/bin/bash

set -e

AWS_ACCOUNT_ID=<ENTER_YOUR_ACCOUNT_ID_HERE>
REGION=us-west-2
ORPHANED_SNAPSHOTS_COUNT_LIMIT=10

WORK_DIR=/tmp

aws ec2 --region $REGION describe-snapshots --owner-ids $AWS_ACCOUNT_ID --query Snapshots[*].SnapshotId --output text | tr '\t' '\n' | sort > $WORK_DIR/all_snapshots
aws ec2 --region $REGION describe-images --filters Name=state,Values=available --owners $AWS_ACCOUNT_ID --query "Images[*].BlockDeviceMappings[*].Ebs.SnapshotId" --output text | tr '\t' '\n' | sort > $WORK_DIR/snapshots_attached_to_ami

ORPHANED_SNAPSHOT_IDS=`comm -23 <(sort $WORK_DIR/all_snapshots) <(sort $WORK_DIR/snapshots_attached_to_ami)`

if [ -z "$ORPHANED_SNAPSHOT_IDS" ]; then
  echo "OK - no orphaned (not attached to any AMI) snapshots found"
  exit 0
fi

ORPHANED_SNAPSHOT_IDS=`echo "$ORPHANED_SNAPSHOT_IDS" | grep "snap"`

ORPHANED_SNAPSHOTS_COUNT=`echo "$ORPHANED_SNAPSHOT_IDS" | wc -l`

if (( ORPHANED_SNAPSHOTS_COUNT > ORPHANED_SNAPSHOTS_COUNT_LIMIT )); then
  echo "CRITICAL - $ORPHANED_SNAPSHOTS_COUNT orphaned (not attached to any AMI) snapshots found: [ $ORPHANED_SNAPSHOT_IDS ]"
  echo "To delete them, use commands below:"
  IFS=$'\n'
  for snapshot_id in $ORPHANED_SNAPSHOT_IDS; do echo "aws ec2 --region us-west-2 delete-snapshot --snapshot-id $snapshot_id"; done
  exit 1
else
  echo "OK - $ORPHANED_SNAPSHOTS_COUNT orphaned (not attached to any AMI) snapshots found"
  if (( ORPHANED_SNAPSHOTS_COUNT > 0 )); then
    echo "[ $ORPHANED_SNAPSHOT_IDS ]"
  fi
  exit 0
fi

0 个答案:

没有答案