我有大约 500 多个 AWS EBS 卷。我可以使用 Volume State = available 和标签将它们过滤掉:year=2022。
我应该如何使用Python或bash脚本批量删除它们,因为我使用控制台一次只能删除50个?
AWS delete-volume 没有“状态”过滤器或“标签”过滤器。
Kenaz Kwa 的 gist 脚本 似乎就是您正在寻找的东西。
#!/usr/bin/env python
import boto3
sess = boto3.Session(
aws_access_key_id="MYAWSACCESSKEYID",
aws_secret_access_key="MYSECRETACCESSKEY",
region_name="us-east-1",
)
ec2 = sess.resource('ec2')
volumes = ec2.volumes.all()
to_terminate=[]
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:
for tag in volume.tags:
if tag['year'] == '2022':
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()
带有代码
if len(volume.attachments) == 0:
的行检查该卷是否已附加到 EC2 实例。您可以根据您的任何标准修改此设置。例如,名称是否以“x”开头,或者大小是否超过 x Gb。