bluethundr
bluethundr

Reputation: 1345

Python boto3 - list indices must be integers or slices, not str

I'm trying to create a list in python and getting an error:

  Traceback (most recent call last):
  File ".\aws_ec2_list_instances.py", line 592, in <module>
    main()
  File ".\aws_ec2_list_instances.py", line 524, in main
    output_file = list_instances(aws_account,aws_account_number, interactive)
  File ".\aws_ec2_list_instances.py", line 147, in list_instances
    regions = set_regions(aws_account)
  File ".\aws_ec2_list_instances.py", line 122, in set_regions
    regions = list((ec2_client.describe_regions()['Regions']['RegionName']))
TypeError: list indices must be integers or slices, not str

Using this code:

import boto3
def set_regions(aws_account):
    try:
        ec2_client = boto3.client('ec2', region_name='us-east-1')
    except Exception as e:
        print(f"An exception has occurred: {e}")

    regions = []
    all_gov_regions = ['us-gov-east-1', 'us-gov-west-1']
    alz_regions = ['us-east-1', 'us-west-2']

    managed_aws_accounts = ['company-lab', 'company-bill', 'company-stage' ]
    if aws_account in managed_aws_accounts:
        if 'gov' in aws_account and not 'admin' in aws_account:
            regions = all_gov_regions
        else:
            regions = list(ec2_client.describe_regions()['Regions']['RegionName'])
            print(f"Regions type: {type(regions)}\n\nRegions: {regions}")
    else:
        regions = alz_regions
    return regions

Previously I had the error in a try block, that's why we weren't seeing much of the error.

I've updated to show the full code and the full error. I've removed the try block on that part of the code to show more of the error.

What am I doing wrong?

Upvotes: 0

Views: 541

Answers (1)

RishiG
RishiG

Reputation: 2830

From the boto3 doc, describe_regions returns a dict of the following form

{
    'Regions': [
        {
            'Endpoint': 'string',
            'RegionName': 'string',
            'OptInStatus': 'string'
        },
    ]
}

Note that response['Regions'] is a list, so you need to index into the list before getting the RegionName. I guess you want something like this:

regions = [reg['RegionName'] for reg in ec2_client.describe_regions()['Regions']]

Upvotes: 1

Related Questions