I’ve been spending a lot of time lately cleaning up AWS resources that are no longer in use. While I am working on a more permanent solution, I came up with a quick couple of CLI commands that help me to see how many disks that I have in the available state that are more than X days old across all regions so that I can delete them. Rather than cut and paste the commands every time I run them, I’ve created a couple of functions that I have added to my dotfiles repo on GitHub.
List Available Volumes Older than X days
aws-av() {
if [ -z "$1" ]; then
echo "Need to include the number of days to list"
else
for region in `aws ec2 describe-regions --output text | cut -f 2|cut -d . -f 2`;
do
echo "-- $region";
aws ec2 describe-volumes \
--region $region \
--filters "Name=status,Values=available" \
--query "Volumes[?CreateTime<='$(date -v -${1}d +%Y-%m-%d)'].VolumeId" \
--output text echo ;
done
fi
}
Cleanup Available Volumes Older than X days
aws-avc() {
if [ -z "$1" ]; then
echo "Needs number of days old to clean up"
else
for region in `aws ec2 describe-regions --output text | cut -f 2|cut -d . -f 2`;
do
echo "-- $region";
for a in `aws ec2 describe-volumes \
--region $region \
--filters "Name=status,Values=available" \
--query "Volumes[?CreateTime<='$(date -v -${1}d +%Y-%m-%d)'].VolumeId" \
--output text`
do
echo "Deleting $a..."
aws ec2 delete-volume --region $region --volume-id $a
done
echo ;
done
fi
}
Once sourced, you can run either function with the number of days old you want the volume to be and it will either list them (aws-av) or remove them (aws-avc).
Comments