简体   繁体   中英

AWS Lambda Boto describe_volumes

I'm new to Python and Lambda and I'm trying to get the list of in-use volumes across all regions.

from datetime import datetime, date
import boto3

def lambda_handler(event, context):
    ec2 = boto3.client('ec2')

    # Get list of regions
    regions = ec2.describe_regions().get('Regions',[] )

    # Iterate over regions
    for region in regions:
        print "Looking at region %s " % region['RegionName']
        reg=region['RegionName']

        # Connect to region
        ec2 = boto3.client('ec2',region_name=reg)

        # Get all in-use volumes    
        volumes = ec2.describe_volumes( Filters=[{'Name': 'status', 'Values': ['in-use']}])

        for volume in volumes:
            print "Looking at volume %s" % volume['VolumeId']

I keep getting the following error and cannot figure out why:

String indices must be integers, not str: TypeError
Traceback (most recent call last):
  File "/var/task/lambda_function.py", line 22, in lambda_handler
    print "Looking at volume %s" % volume['VolumeId']
TypeError: string indices must be integers, not str

volumes is not a dict of volumes.

>>> volumes.keys()
['ResponseMetadata', u'Volumes']

So you need to loop through volumes['Volumes'] . Try this:

for volume in volumes['Volumes']:
    print "Looking at volume %s" % volume['VolumeId']

Output :

Looking at region ap-south-1
Looking at volume vol-1234853ed7652bbb1
Looking at volume vol-00aac56781f21a83
Looking at region eu-west-2
Looking at region eu-west-1
Looking at region ap-northeast-2
Looking at region ap-northeast-1

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM