JavaEar 专注于收集分享传播有价值的技术资料

Function ec2.snapshots.all not iterate boto3 lambda

I am using boto3, for list all snapshots. But when I use function ec2.snapshots.all(), and then try iterate with a for, it's not working.

from __future__ import print_function
from boto3 import resource

REGION = "us-east-1"

def lambda_handler(event, context):
    ec2 = resource("ec2", region_name=REGION)
    all_snapshots = ec2.snapshots.all()
    for snapshot in all_snapshots:
        print("SnapshotIteration")

The result is the next:

{
  "errorMessage": "2017-03-07T00:08:56.583Z 3faed105-02ca-11e7-b637-cfb921e4e3cc Task timed out after 3.00 seconds"
}

1个回答

    最佳答案
  1. I suspect it is listing all publicly-available snapshots, which can be quite a lot. It is better to limit it to snapshots for which you are the owner.

    The describe-snapshots() function takes an OwnerIds parameter that can scope-down the return value.

    Here's an example from the boto3 snapshot documentation that shows how to use a filter on the snapshots iterator:

    snapshot_iterator = ec2.snapshots.filter(
        DryRun=True|False,
        SnapshotIds=[
            'string',
        ],
        OwnerIds=[
            'string',
        ],
        RestorableByUserIds=[
            'string',
        ],
        Filters=[
            {
                'Name': 'string',
                'Values': [
                    'string',
                ]
            },
        ],
        NextToken='string',
        MaxResults=123
    )
    

    That might help.