LambdaCleanupCopiedAMI.py 3.72 KB
Newer Older
Nagarjuna D N's avatar
Nagarjuna D N committed
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
70
71
72
73
#This script deregister the AMI and deletes the associated snapshots for the AMI date of "DeleteOnCopy" expired.

import boto3
import collections
import datetime
import time
import sys

#specify the destination region to AMI's copied to cleanup. Ex: Singapore region (ap-southeast-1)
ec = boto3.client('ec2', 'ap-southeast-1')
ec2 = boto3.resource('ec2', 'ap-southeast-1')
images = ec2.images.filter(Owners=["XXXXX"]) # Specify your AWS account owner id in place of "XXXXX" at all the places in this script

def lambda_handler(event, context):

    to_tag = collections.defaultdict(list)

    date = datetime.datetime.now()
    date_fmt = date.strftime('%d-%m-%Y')
    print "Today's date and time:" + date.strftime('%d-%m-%Y:%H.%m.%s')
    
    imagesList = []
    # Loop through each image of our current instance
    for image in images:
        try:
            if image.tags is not None:
                deletion_date = [
                    t.get('Value') for t in image.tags
                    if t['Key'] == 'DeleteOnCopy'][0]
                
                delete_date = time.strptime(deletion_date, "%d-%m-%Y")
                #print ("deletion_date %s" %delete_date)
                
                #today = datetime.datetime.now()
                #today_date = today.strftime('%d-%m-%Y')
                today_time = datetime.datetime.now().strftime('%d-%m-%Y')
                today_date = time.strptime(today_time, '%d-%m-%Y')
                # print ("today_date %s" %today_date)
                
                # If image's DeleteOn date is less than or equal to today,
                # add this image to our list of images to process later
                if delete_date < today_date:
                    imagesList.append(image.id)
  
        except IndexError:
             deletion_date = False
             delete_date = False
        
        
    print "============="

    print "About to process the following AMIs:"
    print imagesList

    snapshotList = []
    # Loop through each image of our current instance
    for image in imagesList:
        #print image
        desc_image_snapshots = ec.describe_images(ImageIds=[image],Owners=['XXXXX',])['Images'][0]['BlockDeviceMappings']
       # print (desc_image_snapshots)
        try:
            for desc_image_snapshot in desc_image_snapshots:
                snapshot = ec.describe_snapshots(SnapshotIds=[desc_image_snapshot['Ebs']['SnapshotId'],], OwnerIds=['XXXXX'])['Snapshots'][0]
                #if snapshot['Description'].find(image) > 0:
                snapshotList.append(snapshot['SnapshotId'])
                #else:
                #   continue
                #     print "Snapshot is not associated with an AMI"
                
        except Exception as e:
            print "Ignore Index Error:%s" % e.message
            
        print "Deregistering image %s" % image
Nagarjuna D N's avatar
fixes    
Nagarjuna D N committed
74
75
76
        try:
            amiResponse = ec.deregister_image(
                    DryRun=False,
Nagarjuna D N's avatar
Nagarjuna D N committed
77
                ImageId=image,
Nagarjuna D N's avatar
fixes    
Nagarjuna D N committed
78
79
80
81
82
            )
            #print "For testing, commented ami de-register"
        except Exception as e:
            print "%s" % e.message

Nagarjuna D N's avatar
Nagarjuna D N committed
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99

    print "============="
        
    print "About to process the following Snapshots associated with above Images:"
    print (snapshotList)
        
    print "The timer is started for 5 seconds to wait for images to deregister before deleting the snapshots associated to it"    
    time.sleep(5)# This should be set to higher value if the image in the imagesList takes more time to deregister
        
    for snapshot in snapshotList:
        try:
            snap = ec.delete_snapshot(SnapshotId=snapshot)
            print "Deleted snapshot " + snapshot
            
        except Exception as e:
            print "%s" % e.message
    print "-------------"