此程序的目的是删除超过 60 天的快照。 运行时,它显示以下错误" a=快照.start_time属性错误:"dict"对象没有属性"start_time"这是我的代码
#!/usr/bin/env python
import boto3
import datetime
client = boto3.client('ec2')
snapshot= client.describe_snapshots()
for s in snapshot:
a=snapshot[s].start_time
b=a.date()
c=datetime.datetime.now().date()
d=c-b
if d.days>60 :
snapshot[s].delete(dry_run=True)
您的错误在行a=snapshot[s].start_time
,请使用a=s.start_time
请注意,我会将"快照"更改为"快照"。 然后在您的 for 循环中:
for snapshot in snapshots:
这使得代码更易于阅读并清楚变量表示的内容。
另一项是start_time
是一个字符串。您需要解析它才能获得一个数字。下面是一个可以帮助您的示例:
delete_time = datetime.utcnow() - timedelta(days=days)
for snapshot in snapshots:
start_time = datetime.strptime(
snapshot.start_time,
'%Y-%m-%dT%H:%M:%S.000Z'
)
if start_time < delete_time:
***delete your snapshot here***
这应该可以做到-
import boto3
import json
import sys
from pprint import pprint
region = 'us-east-1'
ec2 = boto3.client('ec2', region)
resp = ec2.describe_instances()
resp_describe_snapshots = ec2.describe_snapshots(OwnerIds=['*******'])
snapshot = resp_describe_snapshots['Snapshots']
snapshots = [''];
for snapshotIdList in resp_describe_snapshots['Snapshots']:
snapshots.append(snapshotIdList.get('SnapshotId'))
for id in snapshots:
print(id)