Lambda で EC2 のインスタンスのスナップショットを作成

INSTANCE_ID のスナップショットを作成し、作成したスナップショット数が NUMBER_OF_SNAPSHOTS 数より多い場合は古いスナップショットを削除する。

import boto3
import datetime

INSTANCE_ID = 'xxx'
NUMBER_OF_SNAPSHOTS = 1

def get_instance(ec2_client,instance_id):
    current_instance = None
    for reservation in ec2_client.describe_instances()["Reservations"]:
        for instance in reservation['Instances']:
            if instance['InstanceId'] == instance_id:
                current_instance = instance
    return current_instance

def get_volumd_id(instance):
    return instance['BlockDeviceMappings'][0]['Ebs']['VolumeId']
    
def create_snapshot(ec2_client,instance_id):
    """
    Create a snapshot.
    """
    timestamp = datetime.datetime.now().strftime('%Y%m%d-%H%M%S')
    instance = get_instance(ec2_client,instance_id)
    snapshot = ec2_client.create_snapshot(
    Description='ec2_development_' +timestamp,
    VolumeId=get_volumd_id(instance)
)
    print('Created a snapshot successully.')
    
def get_old_snapshots_by_volume_id(snapshots,volume_id,number_to_keep_snapshots):
    target_snapshots = [snapshot for snapshot in snapshots if snapshot['VolumeId'] == volume_id]
    sorted_target_snapshots = sorted(target_snapshots, key=lambda x: x['StartTime'],reverse=True)
    if len(sorted_target_snapshots) > number_to_keep_snapshots:
        return sorted_target_snapshots[number_to_keep_snapshots:]
    else:
        return []

    
def delete_old_snapshot(ec2_client,instance_id,number_to_keep_snapshots):
    cnt = 0
    instance = get_instance(ec2_client,instance_id)
    snapshots = ec2_client.describe_snapshots(OwnerIds=["self"])['Snapshots']
    volume_id = get_volumd_id(instance)
    for old_snapshot in get_old_snapshots_by_volume_id(snapshots,volume_id,number_to_keep_snapshots):
        ec2_client.delete_snapshot(SnapshotId=old_snapshot['SnapshotId'])
        cnt += 1
    print(f"Deleted {cnt} old snapshots")


def lambda_handler(event, context):
    ec2_client = boto3.client('ec2')
    try:
        create_snapshot(ec2_client,INSTANCE_ID)
        delete_old_snapshot(ec2_client,INSTANCE_ID,NUMBER_OF_SNAPSHOTS)
        return 'SUCCESS'
    except Exception as e:
        print(e)
        return 'ERROR'

Related Contents

Pickup Contents