Skip to content

Instantly share code, notes, and snippets.

@Aminechakr
Created October 18, 2022 17:05
Show Gist options
  • Save Aminechakr/5dd9da6eff7c7a55f800b92dba06978e to your computer and use it in GitHub Desktop.
Save Aminechakr/5dd9da6eff7c7a55f800b92dba06978e to your computer and use it in GitHub Desktop.
#!/usr/bin/env python
import boto3
sess = boto3.Session(
region_name="us-west-2",
)
ec2 = sess.resource('ec2')
volumes = ec2.volumes.all()
to_terminate=[]
def lambda_handler(event, context):
for volume in volumes:
print('Evaluating volume {0}'.format(volume.id))
print('The number of attachments for this volume is {0}'.format(len(volume.attachments)))
# Here's where you might add other business logic for deletion criteria
if len(volume.attachments) == 0:
to_terminate.append(volume)
if len(to_terminate) == 0:
print ("No volumes to terminate! Exiting.")
exit()
for volume in to_terminate:
print('Deleting volume {0}'.format(volume.id))
volume.delete()
@Aminechakr
Copy link
Author

{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Sid": "VisualEditor0",
            "Effect": "Allow",
            "Action": [
                "ec2:DeleteVolume",
                "ec2:ModifyVolume",
                "ec2:DescribeVolumeStatus",
                "ec2:DescribeReplaceRootVolumeTasks",
                "ec2:DescribeVolumes",
                "ec2:DescribeVolumesModifications",
                "ec2:DescribeVolumeAttribute"
            ],
            "Resource": "*"
        }
    ]
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment