Cleanup Unused AWS EC2 EBS Volumes One-Liner

Cleanup Unused AWS EC2 EBS Volumes One-Liner

Terminating the unrequired instances in Amazon Web Services (AWS) EC2 can be a routine job for most of the operations people. But in case they have EBS backed volumes which are protected to ensure they aren’t deleted by instance termination then we might have situation of untracked and unused EBS volumes hanging around. Specially if you have to pay for them!

Working with the console to identify each one of them and deleting them can be tiresome job. Specially if the number of volumes is quiet high.

Fortunately we have aws-cli from AWS which makes life simpler. Personally I am fond of this tool while working on a day-to-day basis.

Cleanup Unused AWS EC2 EBS Volumes One-Liner

The following one-liner does a perfect job of terminating all the unused EBS volumes. Not to mention, I would assume a sound DevOps personel would take a snapshot of the volumes which contain important data before it is delete since it isn’t “In-use”! 🙂

aws ec2 describe-volumes –filters "Name=status,Values=available" --region us-east-1 --output json | python -c "from __future__ import print_function; import json,sys;data=json.load(sys.stdin); [ print(v['VolumeId']) for v in data['Volumes']]" | xargs -n 1 -I % aws ec2 delete-volume –volume-id=% --region us-east-1

Not to mention you will need the required Python modules when you execute this one-liner.

Also, since I don’t like to put in default configuration for any region in my awscli configuration I prefer to mention AWS region on the command line.

Cleanup Unused AWS EC2 EBS Volumes One-Liner


  • Eran

    January 8, 2017 at 10:01 am Reply

    You don’t need Python for that.
    “`aws ec2 describe-volumes –filters “Name=status,Values=available” –region us-east-1 –output text –query ‘Volumes[*].{ID:VolumeId}’ | xargs -n 1 -I % aws ec2 delete-volume –volume-id=% –region us-east-1“`

    • Gagan

      January 8, 2017 at 4:26 pm Reply


      You are right about not having to use Python. Personally I like to deal with the JSON output using Python. But the method you mentioned should work as well.

      Appreciate that suggestion.

Post a Comment

Time limit is exhausted. Please reload CAPTCHA.