Reputation:
Since Amazon switched from ec2-ami-tools to awscli (check this) Robert Sindall's solution is no longer acceptable.
So I decided to rewrote his script for new python/json standards.
Feel free to ask any questions or provide your solution.
Upvotes: 0
Views: 784
Reputation:
Please, install and configure awscli properly. For MacOS I would recommend brew version.
After installation don't forget to run aws configure
Works flawlessly for me but anyway USE IT AT YOUR OWN RISK.
import json, subprocess
def remove_unused_snaps(region):
line = 'aws ec2 describe-images --region {} --owners self'.format(region)
p = subprocess.Popen(line.split(),
stdout=subprocess.PIPE, stderr=subprocess.PIPE)
out, err = p.communicate()
obj = json.loads(out.decode("utf-8"))
snaps_used = set(i['BlockDeviceMappings'][0]['Ebs']['SnapshotId'] for i in obj['Images'])
line = 'aws ec2 describe-snapshots --region {} --owner-ids self'.format(region)
p = subprocess.Popen(line.split(),
stdout=subprocess.PIPE, stderr=subprocess.PIPE)
out, err = p.communicate()
obj = json.loads(out.decode("utf-8"))
snaps_old = set(i['SnapshotId'] for i in obj['Snapshots'])
line = 'aws ec2 delete-snapshot --region {} --snapshot-id'.format(region)
for snap in list(snaps_old - snaps_used):
p = subprocess.Popen(line.split() + [snap],
stdout=subprocess.PIPE, stderr=subprocess.PIPE)
out, err = p.communicate()
print(snap, out, err)
Then simply run it: remove_unused_snaps('us-west-2')
Upvotes: 1