如何使用python boto3在我的aws帐户中显示所有快照

时间:2017-11-15 05:36:00

标签: python amazon-web-services boto3

此程序的目的是删除超过60天的快照。运行时显示以下错误"一个快照= [S] .start_time AttributeError:' 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)

2 个答案:

答案 0 :(得分:1)

您的错误在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***

答案 1 :(得分:0)

这应该做到-

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)