vishal
vishal

Reputation: 1874

how to display all snapshots in my aws account using python boto3

the aim of this program is to delete snapshots that are older than 60 days. when run it displays the following error " a=snapshot[s].start_time AttributeError: 'dict' object has no attribute 'start_time' " This is my code

    #!/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)

Upvotes: 1

Views: 2309

Answers (2)

Paresh Sahasrabudhe
Paresh Sahasrabudhe

Reputation: 41

This should do it-

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)

Upvotes: 1

John Hanley
John Hanley

Reputation: 81346

Your error is in the line a=snapshot[s].start_time, use a=s.start_time

Note I would change "snapshot" to "snapshots". then in your for loop:

for snapshot in snapshots:

This makes the code easier to read and clear on what your variables represent.

Another item is that start_time is a string. You will need to parse this to get a number. Here is an example to help you:

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***

Upvotes: 1

Related Questions