Last active
December 12, 2019 17:55
-
-
Save nmagee/1894d6a734821bb30011a313b0106247 to your computer and use it in GitHub Desktop.
Lambda function for creating AMIs of your entire EC2 region.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| # Written for AWS Lambda, for the Python 3.6 runtime. | |
| import json | |
| import boto3 | |
| import datetime | |
| ## Be sure to set account number on line 57. | |
| ## Set DRY RUN value - for testing or running. | |
| dryrun = False | |
| ec2 = boto3.client('ec2') | |
| today = datetime.date.today() | |
| weekago = today - datetime.timedelta(days=7) | |
| todayz = today.strftime("%Y%m%d") | |
| weekagoz = weekago.strftime("%Y%m%d") | |
| weekfilter = "*" + weekagoz | |
| todayfilter = "*" + todayz | |
| def lambda_handler(event, context): | |
| response = ec2.describe_instances( | |
| MaxResults=99 | |
| ) | |
| ids = [] | |
| for r in response['Reservations']: | |
| for i in r['Instances']: | |
| # print i['InstanceId'] | |
| ids.append(i['InstanceId']) | |
| for instance in ids: | |
| AmiName = instance + '-' + str(todayz) | |
| response = ec2.create_image( | |
| DryRun=dryrun, | |
| InstanceId=instance, | |
| NoReboot=True, | |
| Name=AmiName, | |
| Description='Weekly backup AMI run via Lambda' | |
| ) | |
| remove_old() | |
| print("AMI Creation completed") | |
| def remove_old(): | |
| response = ec2.describe_images( | |
| Filters=[ | |
| { | |
| 'Name': 'name', | |
| 'Values': [ | |
| weekfilter, | |
| ] | |
| }, | |
| ], | |
| Owners=[ | |
| '123456789012', | |
| ], | |
| ) | |
| ids = [] | |
| for r in response['Images']: | |
| ids.append(r['ImageId']) | |
| for id in ids: | |
| del_response = ec2.deregister_image( | |
| ImageId=id, | |
| DryRun=dryrun | |
| ) | |
| print(del_response) | |
| print("AMI Deletion completed - for week-old images") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment