読者です 読者をやめる 読者になる 読者になる

set setting reset

インフラ関連の小ネタと備忘録

boto3 で指定された日付以前の snapshot を削除する

python

という python script を晒してみます。

#!/usr/bin/env python
# -*- coding: utf-8 -*-

"""
指定された日付以前の snapshot を削除します
ただし ami に紐付いている snapshot は削除しません

example:
    $ python delete_expired_snapshots.py -p profile_name -o owner_id -e expire_date (--dry-run True|False)
"""

import boto3
import pytz
from argparse import ArgumentParser
from datetime import datetime, timedelta


def delete_expired_snapshots(profile, owner_id, expire_date, dry_run=False,):
    session = boto3.Session(profile_name=profile)
    client = session.client("ec2")
    snapshots = client.describe_snapshots(OwnerIds=[owner_id])
    """
    response example:
        "Snapshots": {
            u'Description': '***********',
            u'Encrypted': True,
            u'VolumeId': 'vol-*****',
            u'KmsKeyId': 'arn:aws:kms:region:*******:key/***********',
            u'State': 'completed',
            u'VolumeSize': **,
            u'Progress': '100%',
            u'StartTime': datetime.datetime(yyyy, mm, dd, hh, MM, SS, tzinfo=tzutc()),
            u'SnapshotId': 'snap-************',
            u'OwnerId': '*******'
        },...
    """
    expired_snapshot_ids = [ s["SnapshotId"] for s in snapshots["Snapshots"]
        if s["StartTime"] < expire_date ]
    for expired_snapshot_id in expired_snapshot_ids:
        try:
            res = client.delete_snapshot(SnapshotId=expired_snapshot_id, DryRun=dry_run)
            if res["ResponseMetadata"]["HTTPStatusCode"] == 200:
                print("INFO. delete Succeed id:{0}".format(expired_snapshot_id))
            else:
                print("ERROR. delete Failed id:{0} status_code:{1}".format(
                    expired_snapshot_id, res))
        except Exception as e:
            print("ERROR. exception occurd id:{0}".format(expired_snapshot_id))
            print("Exception. {0}".format(e))


def arg_parse_for_delete_expired_snapshots():
    parser = ArgumentParser()
    parser.add_argument(
        "-p", "--profile", dest="profile",
        type=str, required=True,
        help="specify snapshots aws profile"
    )
    parser.add_argument(
        "-o", "--owner-id", dest="owner_id",
        type=str, required=True,
        help="specify snapshots owner_id"
    )
    parser.add_argument(
        "-e", "--expire-date", dest="expire_date",
        type=int, required=True,
        help="specify expire date"
    )
    parser.add_argument(
        "--dry-run", dest="dry_run",
        type=bool,
        default=False,
        help="dry run switch"
    )
    return parser.parse_args()
    

if __name__ == "__main__":
    p = arg_parse_for_delete_expired_snapshots()
    expire_date = datetime.now(pytz.utc) - timedelta(p.expire_date)
    delete_expired_snapshots(p.profile, p.owner_id, expire_date, p.dry_run)