Remove AMI and its snapshots, automatically

Given that you have setup the access key and secret keys (or roles as I prefer), I have created a BASH script to:

  1. Deregister a list of AMIs
  2. Delete the corresponding snapshots of the deregistered AMIs.
  3. Make note of region and profile being used in the script.
    You can copy the below script (make changes accordingly):
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
#!/bin/bash

#input file should contain spaces separated ami IDs. Example: ami-abcd1234 ami-1234abcd ami-1a2b3c4d
usage () {
echo '
Usage: '"$SCRIPT_NAME"' <List of AMI IDs>
E.g.
'"$SCRIPT_NAME"' ami-abcd1234 ami-1234abcd ami-1a2b3c4d .. .. ..
'
}

if [ "$#" == 0 ]
then
usage
else
alias aws=''`which aws`' --profile <profile> --region <region>'
shopt -s expand_aliases
echo $@
aws ec2 describe-images --image-ids $@ --query 'Images[*].BlockDeviceMappings[*].Ebs.SnapshotId' | sed 's,\t,\n,g' > del_snapshots.csv
for i in $@; do
echo $i
aws ec2 deregister-image --image-id $i
done
cat del_snapshots.csv
while read SNAP_ID; do
aws ec2 delete-snapshot --snapshot-id "$SNAP_ID"
done < del_snapshots.csv
unalias aws
fi
amazon web services aws cloud instance linux ubuntu ami ec2 centos redhat unix amazon image snapshot vpc