Skip to content

Instantly share code, notes, and snippets.

@spinolacastro
Created October 23, 2014 00:39
Show Gist options
  • Select an option

  • Save spinolacastro/dbda4cee5b919af2a31f to your computer and use it in GitHub Desktop.

Select an option

Save spinolacastro/dbda4cee5b919af2a31f to your computer and use it in GitHub Desktop.
prune-snapshots
#!/bin/bash
source /etc/profile
set -x
CMD_SNAPSHOT_DESCRIBE=ec2-describe-snapshots
CMD_SNAPSHOT_DELETE=ec2-delete-snapshot
CMD_TAG_DESCRIBE=ec2-describe-tags
CMD_TAG_CREATE=ec2-create-tags
REGIONS="sa-east-1"
for region in $REGIONS; do
snapshots=( $($CMD_SNAPSHOT_DESCRIBE --region $region --filter "start-time=$(date --date="2 week ago" +%Y-%m-%d*)" | grep "SNAPSHOT" | awk '{ print $2 }' ))
# Snapshots initiated, delete old snapshots
echo -e "Snapshots initiated, delete old snapshots...\r"
for snapshot in ${snapshots[@]}
do
result=$($CMD_SNAPSHOT_DELETE --region $region "$snapshot" 2>&1)
echo $result
# This does not currently work as the result of the delete command cannot be captured
if [[ "$result" == *"Client.InvalidSnapshot.InUse"* ]]; then
echo -e " Error: Could not delete snapshot $snapshot because it is currently in use by an AMI, renaming accorindgly."
volume_id=$($CMD_SNAPSHOT_DESCRIBE --region $region "$snapshot" | grep "SNAPSHOT" | awk '{print $3}')
volume_name=`$CMD_TAG_DESCRIBE --region $region --filter "resource-id=$volume_id" --filter "key=Name" | cut -f5`
current_date=$(date +%Y-%m-%d)
snapshot_label="$current_date: [AMI] $volume_name"
echo -e " Labeling snapshot $snapshot as \"$snapshot_label\""
$CMD_TAG_CREATE $snapshot --region $region --tag "Name=$snapshot_label"
fi
done
done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment