xrogue

AWS Lambda AMI Replicator Bot Code

Jul 24th, 2018
395
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 4.19 KB | None | 0 0
  1. # This script copies the AMI to other region and add tag 'DeleteOnCopy' with retention days specified.
  2. import boto3
  3. from dateutil import parser
  4. import datetime
  5. import collections
  6.  
  7. # Set the global variables
  8. globalVars  = dict()
  9. globalVars['Owner']                 = 'user'
  10. globalVars['Environment']           = 'env_name'
  11. globalVars['SourceRegion']          = 'ap-south-1'
  12. globalVars['destRegions']           = ['us-east-1','us-east-2',]        # List of AWS Regions to which the AMI to be copied
  13. globalVars['amiRetentionDays']      = int(5)                # AMI Rentention days in DR/Destination Region.
  14.  
  15. # Create the Boto Resources and Clients
  16. srcEC2Resource  = boto3.resource('ec2', region_name = globalVars['SourceRegion'])
  17.  
  18. # Get the Account ID of the Lambda Runner Account - Assuming this is the source account
  19. globalVars['awsAccountId']          = boto3.client('sts').get_caller_identity()['Account']
  20.  
  21. def img_replicator():
  22.  
  23.     # Get the list of images in source Region
  24.     images = srcEC2Resource.images.filter(Owners=[ globalVars['awsAccountId'] ])
  25.  
  26.     to_tag = collections.defaultdict(list)
  27.  
  28.     imgReplicationStatus = {'Images': []}
  29.  
  30.     for image in images:
  31.         image_date = parser.parse(image.creation_date)
  32.  
  33.         # Copy ONLY today's images
  34.         if image_date.date() == (datetime.datetime.today()).date():
  35.  
  36.         # To Copy previous day images
  37.         # if image_date.date() == (datetime.datetime.today()-datetime.timedelta(1)).date():
  38.  
  39.             # Copy to Multiple destinations
  40.             for awsRegion in globalVars['destRegions']:
  41.  
  42.                 destEC2Client = boto3.client('ec2', region_name=awsRegion)
  43.  
  44.                 # Copy ONLY if the destination doesn't have an image already with the same name
  45.                 # AMI Names have to be UNIQUE
  46.                 if not destEC2Client.describe_images(Owners=[ globalVars['awsAccountId'] ], Filters=[{'Name':'name', 'Values':[image.name]}])['Images']:
  47.  
  48.                     print "Copying Image. \nImage Name:{name} \nID:{id} \nRegion:'{dest}'".format(name=image.name,id=image.id, dest=awsRegion)
  49.  
  50.                     new_ami = destEC2Client.copy_image(
  51.                         DryRun=False,
  52.                         SourceRegion=globalVars['SourceRegion'],
  53.                         SourceImageId=image.id,
  54.                         Name=image.name,
  55.                         Description=image.description
  56.                     )
  57.  
  58.                     to_tag[ globalVars['amiRetentionDays'] ].append(new_ami['ImageId'])
  59.  
  60.                     imgReplicationStatus['Images'].append({'Source-Image-Id':image.id,
  61.                                                            'Destination-Image-Id':new_ami['ImageId'],
  62.                                                            'RetentionDays':globalVars['amiRetentionDays'],
  63.                                                            'Status':'Copied'})
  64.  
  65.                     for ami_retention_days in to_tag.keys():
  66.                         delete_date = datetime.date.today() + datetime.timedelta(days=globalVars['amiRetentionDays'])
  67.                         delete_fmt = delete_date.strftime('%d-%m-%Y')
  68.                         print "Will delete {0} AMIs on {1}".format(len(to_tag[globalVars['amiRetentionDays']]), delete_fmt)
  69.  
  70.                         # Add tag to the AMI enabling Lambda to delete/cleanUp after retention period expires
  71.                         destEC2Client.create_tags( Resources=to_tag[globalVars['amiRetentionDays']],
  72.                                                    Tags=[ {'Key': 'DeleteOnCopy', 'Value': delete_fmt} ]
  73.                                                  )
  74.                 else:
  75.                     print "Image {name} - {id} already present in Virginia Region".format( name=image.name, id=image.id )
  76.                     imgReplicationStatus['Images'].append({'AMI-Id':image.id,'Status':'Already Exists'})
  77.  
  78.  
  79.         else:
  80.             print "There are no new images. The Image: {name} with AMI ID: {id} was created on {date}".format(name=image.name, id=image.id, date=image_date.strftime('%d-%m-%Y'))
  81.  
  82.     return imgReplicationStatus
  83.  
  84.  
  85. def lambda_handler(event, context):
  86.     img_replicator()
  87.  
  88. if __name__ == '__main__':
  89.     lambda_handler(None, None)
Advertisement
Add Comment
Please, Sign In to add comment