-
Notifications
You must be signed in to change notification settings - Fork 0
/
aws-delete-ec2-ami-images
executable file
·69 lines (60 loc) · 2.02 KB
/
aws-delete-ec2-ami-images
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
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
#!/bin/bash
set -x
# set default values for options
threshold_date=''
region='us-east-1'
profile=''
# define usage function
usage() {
echo "Usage: $(basename "$0") -d DATE [-r REGION] -p PROFILE" >&2
echo "Delete AMI images older than a specified date in batches of 10" >&2
echo " -d DATE Image creation date threshold (YYYY-MM-DD)" >&2
echo " -r REGION AWS region (default: us-east-1)" >&2
echo " -p PROFILE AWS CLI profile name" >&2
echo " -h Display this help message and exit" >&2
}
# parse command line options
while getopts "d:r:p:h" opt; do
case $opt in
d)
threshold_date="$OPTARG"
;;
r)
region="$OPTARG"
;;
p)
profile="$OPTARG"
;;
h)
usage
exit 0
;;
\?)
usage
exit 1
;;
esac
done
# check for required options
if [[ -z "$threshold_date" || -z "$profile" ]]; then
echo "Error: Date threshold and profile not specified" >&2
usage
exit 1
fi
# get a list of AMI images older than the threshold date owned by the current user
image_ids=$(aws ec2 describe-images --owners self --filters Name=creation-date,Values="$threshold_date" --query 'Images[*].[ImageId]' --output text --region "$region" --profile "$profile")
# check if there are any images to delete
if [[ -z "$image_ids" ]]; then
echo "No images found older than $threshold_date."
exit 0
fi
# loop through the array of image IDs and delete them in batches of 10
for image_id in $image_ids; do
echo "Deregistering image $image_id..."
if aws ec2 describe-images --image-ids "$image_id" --region "$region" --profile "$profile" >/dev/null 2>&1; then
aws ec2 deregister-image --image-id "$image_id" --region "$region" --profile "$profile" || echo "Failed to deregister image $image_id"
else
echo "Image $image_id not found, skipping..."
fi
done
echo "All images older than $threshold_date have been processed."