matt
matt

Reputation: 44293

Python Lambda: Delete Snapshots but Exclude by Tag

I'm fairly new to python and writing lambda functions on AWS. I read a lot of blogposts and articles now and eventually stumbled over the following script that I'm currently "testing".

        … 
        # Connect to region
        ec2 = boto3.client('ec2', region_name=reg)
        
        # grab all snapshot id's
        result = ec2.describe_snapshots( OwnerIds=[account_id] )
        # result = ec2.describe_snapshots( Filters=[{'Name': 'tag:retention', 'Values': ['keep']},{'Name': 'owner-id','Values': ['111111111111']}] )
    
        for snapshot in result['Snapshots']:
            print "Checking snapshot %s which was created on %s" % (snapshot['SnapshotId'],snapshot['StartTime'])

            # for tag in snapshots:

            … 
        
        

What I'm after is that I delete all snapshots older then the retention days BUT with the exception of all snapshots that have a tag "retention" with value "keep".

Can anyone help me out here on how to do that inside the for loop?

The question is: Do I even do that in the for loop and filter somehow snapshot[Tags] or something or do I use a filter above?

I guess if I use the filter within describe_snapshots I only get the snapshots with the tag. But I want to retrieve all snapshots and then run the delete command for all but the ones with the tag.

Help would be appreciated. Thanks in advance

Upvotes: 0

Views: 952

Answers (1)

saranjeet singh
saranjeet singh

Reputation: 888

At first, I list all the snapshots ID which need to retain in not_delete_snaps list. and then calculated retention_days. You can change as per your need. Finally, loop all the snapshots and checked if snashot id is exist in not_delete_snaps. If exist, then dont do anything, just continue. Then checked if snapshot ID is older than retention_days. if yes then deleting all the older snapshots.

import boto3
from datetime import datetime
from datetime import timedelta
from botocore.exceptions import ClientError


def lambda_handler(event, context):
    ec2_client = boto3.client('ec2')

    snap_list = []
    marker = None
    paginator = ec2_client.get_paginator('describe_snapshots')
    while True:
        page_iterator = paginator.paginate(
            OwnerIds=['111111111111'],
            PaginationConfig={
                # 'MaxItems': 100,
                'PageSize': 100,
                'StartingToken': marker
            }
        )
        for page in page_iterator:
            snap_list += page['Snapshots']
        try:
            marker = page['Marker']
        except KeyError:
            break

    retention_days = datetime.now() - timedelta(days=7)
    for item in snap_list:
        start_time = item['StartTime']
        start_time_new = start_time.replace(tzinfo=None)
        keys = list(item.keys())
        try:
            if 'Tags' in keys and item['Tags'][0]['Key'] == 'retention' and item['Tags'][0]['Value'] == 'keep':
                continue
            if retention_days > start_time_new:
                ec2_client.delete_snapshot(
                    SnapshotId=item['SnapshotId'])
        except ClientError as e:
            if e.response['Error']['Code'] == 'InvalidSnapshot.InUse':
                print('Skipping snapshots which are in use')
            else:
                print("Unexpected error: %s" % e)

Upvotes: 1

Related Questions