Thursday, March 6, 2014

AWS CLI memorandum - Delete Available EBS Volumes

We sometimes need to delete or remove unnecessary resources which we forgot to do so when we are creating some resources on AWS, don't we? I'm making a note mainly with AWS CLI for those situations.

Today, we are deleting all of the available EBS volumes!

* Describe EBS Volumes
$ aws ec2 describe-volumes| jq '.Volumes[0]'
{
  "Size": 10,
  "AvailabilityZone": "ap-northeast-1a",
  "Attachments": [
    {
      "Device": "/dev/sda",
      "DeleteOnTermination": true,
      "State": "attached",
      "VolumeId": "vol-xxxxxxxx",
      "InstanceId": "i-xxxxxxxx",
      "AttachTime": "2013-09-30T02:16:37.000Z"
    }
  ],
  "VolumeType": "standard",
  "VolumeId": "vol-xxxxxxxx",
  "State": "in-use",
  "SnapshotId": "snap-xxxxxxxx",
  "CreateTime": "2013-09-30T02:16:37.000Z"
}

* Extract available EBS Volumes
$ aws ec2 describe-volumes| jq '.Volumes[] | select(.State == "available") | {VolumeId,State}'
{
  "State": "available",
  "VolumeId": "vol-xxxxxxxx"
}
...
{
  "State": "available",
  "VolumeId": "vol-xxxxxxxx"
}
$ aws ec2 describe-volumes| jq '.Volumes[] | select(.State == "available")' | jq '.VolumeId' | sed -e 's/"//g'
vol-xxxxxxxx
...
vol-xxxxxxxx

* Delete available EBS Volumes in dry-run mode
$ for i in `aws ec2 describe-volumes| jq '.Volumes[] | select(.State == "available")' | jq '.VolumeId' | sed -e 's/"//g'`
  do aws ec2 delete-volume --volume-id $i --dry-run
done
A client error (DryRunOperation) occurred: Request would have succeeded, but DryRun flag is set.

* Delete available EBS Volumes
$ for i in `aws ec2 describe-volumes| jq '.Volumes[] | select(.State == "available")' | jq '.VolumeId' | sed -e 's/"//g'`
  do aws ec2 delete-volume --volume-id $i
done
{
    "return": "true"
}
...
{
    "return": "true"
}

* Confirm available EBS Volumes deleted
$ aws ec2 describe-volumes| jq '.Volumes[] | select(.State == "available") | {VolumeId,State}'

Make sure that unnecessary resources have been released to save cost!

1 comment:

iJAWS@Doorkeeper