Python boto3 - индексы в списке должны быть целыми или кусочками, а не str - PullRequest
0 голосов
/ 20 ноября 2019

Я пытаюсь создать список в Python и получаю сообщение об ошибке:

  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

Используя этот код:

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

Ранее у меня была ошибка в блоке try,вот почему мы не видели большую часть ошибки.

Я обновил, чтобы показать полный код и полную ошибку. Я удалил блок try в этой части кода, чтобы показать больше ошибок.

Что я делаю не так?

1 Ответ

1 голос
/ 20 ноября 2019

С документ boto3 , describe_regions возвращает указание в следующей форме

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

Обратите внимание, что response['Regions'] - это список, поэтому вам нужно проиндексировать его. до получения RegionName. Я думаю, вы хотите что-то вроде этого:

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