Python boto3 - 列表索引必须是整数或切片,而不是 str

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

我正在尝试在 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 块以显示更多错误。

我做错了什么?

来自the boto3 docdescribe_regions returns 一个如下形式的字典

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

注意response['Regions']是一个列表,所以你需要在获取RegionName之前对列表进行索引。我猜你想要这样的东西:

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