我正在尝试在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 doc,describe_regions
返回以下形式的字典
{
'Regions': [
{
'Endpoint': 'string',
'RegionName': 'string',
'OptInStatus': 'string'
},
]
}
请注意,response['Regions']
是一个列表,因此在获取RegionName
之前需要索引到列表。我想你想要这样的东西:
regions = [reg['RegionName'] for reg in ec2_client.describe_regions()['Regions']]