Created
October 25, 2017 05:26
-
-
Save nazo/57b6bb3215868470e2685a8642e519c1 to your computer and use it in GitHub Desktop.
AWS EC2 standalone snapshot (not related AMI) check script
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
# standalone AWS snapshot (no related AMI) check script | |
# AMIが存在しない自己所有スナップショットを発見&削除するスクリプト | |
from __future__ import print_function | |
import boto3 | |
import sys | |
def each_snapshots(client): | |
next_token = "" | |
while True: | |
response = client.describe_snapshots( | |
MaxResults=100, | |
OwnerIds=["self"], | |
NextToken=next_token, | |
) | |
if len(response["Snapshots"]) == 0 or "NextToken" not in response: | |
break | |
for snapshot in response["Snapshots"]: | |
yield snapshot | |
next_token = response["NextToken"] | |
def find_ami(client, snapshot_id): | |
image = client.describe_images( | |
Filters=[ | |
{ | |
"Name": "block-device-mapping.snapshot-id", | |
"Values": [snapshot_id], | |
} | |
] | |
) | |
if len(image["Images"]) == 0: | |
return False | |
return image["Images"][0] | |
def delete_snapshot(ec2, snapshot_id): | |
snapshot = ec2.Snapshot(snapshot_id) | |
snapshot.delete() | |
if __name__ == "__main__": | |
client = boto3.client("ec2") | |
ec2 = boto3.resource("ec2") | |
count = 0 | |
delete = len(sys.argv) > 1 and sys.argv[1] == "--delete" | |
for snapshot in each_snapshots(client): | |
snapshot_id = snapshot["SnapshotId"] | |
ami = find_ami(client, snapshot_id) | |
if not ami: | |
print("snapshot ID {0} (created at {1:%Y-%m-%d}) is not found AMI.".format(snapshot["SnapshotId"], snapshot["StartTime"])) | |
count += 1 | |
if delete: | |
delete_snapshot(ec2, snapshot_id) | |
print("deleted.") | |
print("{} snapshots found.".format(count)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment