Deleting EC2 Volumes with the Status of “Available”

Occasionally you might find your self with lots of “available” EC2 volumes that are not attached to any EC2 Instances. If you find yourself wanting to delete them then this little powershell snippet can help. NOTE: I will create a shell / Awk based snippet at some point also for the Linux / Mac users

WARNING: USE WITH CAUTION

This little snippet only checks for the “available” status on your volume. Which means it only checks if the volume is unattached to a running AMI instance. It doesn’t check if there is any valuable data on the volumes. Please USE WITH CAUTION as it deletes all the volumes with status “available”. DON’T DO ANYTHING SILLY If in doubt don’t do it.

Requirements

Not much, simply that you have PowerShell EC2-CLI running on your Windows workstation.

The Code

$volumes = ec2-describe-volumes --region eu-west-1 | select-string -Pattern available #Find volumes not attached to an instance 
 
foreach ($volume in $volumes) {  #Loop through the volumes and extract the volume id and then delete each one
 $volume_string = $volume.ToString()
 $volume_string = $volume_string.Split()
 ec2-delete-volume --region eu-west-1 $volume_string[1]

The first line of the code gets a list of the volumes with the status set to available. The second foreach loop goes each of the lines converts them into string, splits the string into chunks (elements delimited by spaces).
Finally the ec2-delete-volume command uses the 2nd chunk/element as the volume id.

How to use it

Paste the above into a file with .ps1 extension e.g ec2_delete_available_volume.ps1 then run the file as a powershell scripts e.g .\ec2_delete_available_volume.ps1. The script will quietly go away and delete the available ec2 block storage volumes.
delete_ec2_voumes_powershell

Confirm that it has removed the volumes via the console or via the ec2-describe-volumes command.

Comments are closed.