Showing posts with label AWS. Show all posts
Showing posts with label AWS. Show all posts

Wednesday, 12 October 2016

To delete old volume / snapshots :-

# cat getallsnap.sh

#/bin/bash
aws ec2 describe-snapshots --owner-ids 123456789 --filters Name=status,Values=completed |grep snap | awk '{print $9 " " $8}' | cut -d 'T' -f 1-3 --output-delimiter=' ' | awk '{print $1 " " $3}' > allsnap.txt

for i in `cat allsnap.txt | awk '{print $1}'`
do
if [ "$i" == "$(date +%Y-%m-%d --date '1 days ago')" ];
then
echo "1 days older SNAPSHOT ID is stored in snapid.txt file"
grep $i allsnap.txt | awk '{print $2}' > snapid.txt

else
echo "No older SNAPSHOT Image found"
fi
done


## create second bash script as below  snapdelete.sh

#/bin/bash
for i in `cat /root/snapid.txt`;do aws ec2 delete-snapshot --snapshot-id $i ; done

:wq


Cron Job :

30 6 * * * /bin/sh /root/getallsnap.sh >> /root/getallsnap.txt
33 6 * * * /bin/sh /root/snapdelete.sh >> /root/snapdelete.txt

AWS Script TO Delete Old AMI and There Asociated Snapshots.



AWS Script TO Delete Old AMI and There Asociated Snapshots.


# To collect all amis from specific account in to single file called allAMI.txt
#!/bin/bash
aws ec2 describe-images --region ap-southeast-1 --owners 121212123456 | grep ami | awk '{print $3 " " $9}' | cut -d 'T' -f 1-3 --output-delimiter=' ' | awk '{print $1 " " $3}' > allAMI.txt

for i in `cat allAMI.txt | awk '{print $1}'`
do
if [ "$i" == "$(date +%Y-%m-%d --date '3 days ago')" ];
then
echo "3 days older AMI ID is stored in amiid.txt file"
grep $i allAMI.txt | awk '{print $2}' > amiid.txt

else
echo "No older AMI image found"
fi
done

============================

## This script used to delete ami and snapshots:


cat ami-delete.sh

#Find snapshots associated with AMI.
aws ec2 describe-images --image-ids `cat /root/amiid.txt` | grep snap | awk ' { print $4 }' > /root/snap.txt

echo -e "Following are the snapshots associated with it : `cat /root/snap.txt`:\n "

echo -e "Starting the Deregister of AMI... \n"

#Deregistering the AMI
for i in `cat /root/amiid.txt` ; do aws ec2 deregister-image --image-id $i ; done

echo -e "\nDeleting the associated snapshots.... \n"

#Deleting snapshots attached to AMI
for i in `cat /root/snap.txt`;do aws ec2 delete-snapshot --snapshot-id $i ; done
sleep 3
> allAMI.txt
> snap.txt



## Setup cron jobs for Auto Delete AMI - Snapshots

30 3 * * * /bin/sh /root/main.sh >> /root/main-log.txt
33 3 * * * /bin/sh /root/ami-delete.sh >> /root/ami-delete.txt