Python Forum

Full Version: AWS lambda python help
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hello All,

I have the following , but when I try to run it nothing happens from the command line.I am using ubuntu 16, and I have everything configured in my ~/.aws/config and credentials file. I have snapshots configured in aws tags
Quote:DeleteOn 2018-02-06

The part I added was regarding the deleting of snapshots based on the tags[Value], I am new to python, but the logic seems fair, can you offer some help please.

Thank you

import boto3
import re
import datetime

ec = boto3.client('ec2')
iam = boto3.client('iam')

def lambda_handler(event, context):
    account_ids = list()
    try:
       iam.get_user()
    except Exception as e:
        # use the exception message to get the account ID the function executes under
        account_ids.append(re.search(r'(arn:aws:sts::)([0-9]+)', str(e)).groups()[1])


    delete_on = datetime.date.today().strftime('%Y-%m-%d')
    filters = [
        {'Name': 'tag-key', 'Values': ['DeleteOn']},
    ]
    snapshot_response = ec.describe_snapshots(OwnerIds=account_ids, Filters=filters)
    print "Number of results %s " % len(snapshot_response)
    resultcount += len(snapshot_response)
    for snap in snapshot_response['Snapshots']:
               if 'Tags' in snap:
                    for tag in snap['Tags']:
                        if tag['Key'] == "DeleteOn":
                            deleteon = datetime.datetime.strptime(tag['Value'], "%Y-%m-%d")
                            print "deleteon is %s" % str(deleteon)
                            if deleteon <= today:
                                print "Deleting snapshot (removed so far %s)" % deletecount
                                ec.delete_snapshot( SnapshotId=snap['SnapshotId'] )
                                deletecount += 1
                            else:
                                print "Not deleteing snapshot, not old enough"
               else:
                   print "no tags found, can\'t be mine"
                   print "end of snapshots ( %s found , %s deleted )" % ( resultcount, deletecount )