我正在尝试删除旧的AWS快照,但是我需要排除任何描述值以“ Created by CreateImage”开头的快照。
我尝试了boto3.resource和boto3.client的变体。
from datetime import datetime, timedelta, timezone
import boto3
client = boto3.client('ec2')
snapshots = client.snapshots.filter(Description!='Created by CreateImage')
def lambda_handler(event, context):
for snapshot in snapshots:
start_time = snapshot.start_time
delete_time = datetime.now(tz=timezone.utc) - timedelta(days=790)
if delete_time > start_time:
snapshot.delete()
print('Snapshot with Id = {} is deleted '.format(snapshot.snapshot_id))
现在,我有大约10张超过790天的快照,其中5张快照的描述以“ CreateImage by CreateImage”开头,而5张快照没有。在测试时,我想删除没有说明的那些快照。
我得到的错误是:
模块初始化错误:“ EC2”对象没有属性“快照”
答案 0 :(得分:0)
您需要使用describe_snapshots
并正确传入过滤器。
此外,结果将是字典,而不是对Snapshot类的引用,因此您需要更新提取属性和删除快照的方式。
类似的东西:
from datetime import datetime, timedelta, timezone
import boto3
client = boto3.client('ec2')
snapshots = client.describe_snapshots(Filters=[
{
'Name': 'description',
'Values': [
'Created by CreateImage',
]
},
])['Snapshots']
def lambda_handler(event, context):
for snapshot in snapshots:
start_time = snapshot['StartTime']
delete_time = datetime.now(tz=timezone.utc) - timedelta(days=790)
if delete_time > start_time:
client.delete_snapshot(SnapshotId=snapshot['SnapshotId'])
print('Snapshot with Id = {} is deleted '.format(snapshot['SnapshotId']))
答案 1 :(得分:0)
这是一个可行的版本。
请注意使用OwnerIds=['self']
,它将结果限制为仅由您的AWS账户创建的快照。否则,它将返回任何AWS账户创建的所有公共可用快照。
from datetime import datetime, timedelta, timezone
import boto3
def lambda_handler(event, context):
delete_time = datetime.now(tz=timezone.utc) - timedelta(days=790)
ec2_resource = boto3.resource('ec2', region_name='ap-southeast-2')
snapshots = ec2_resource.snapshots.filter(OwnerIds=['self'])
for snapshot in snapshots:
if not snapshot.description.startswith('Created by CreateImage') and delete_time > snapshot.start_time:
snapshot.delete()
print('Snapshot with Id = {} is deleted '.format(snapshot.snapshot_id))