简体   繁体   English

如何使用Boto3(Python)列出可用区域

[英]How to list available regions with Boto3 (Python)

As AWS expands and adds new regions, I'd like to have my code automatically detect that. 随着AWS扩展并添加新区域,我希望我的代码能够自动检测到这一点。 Currently, the "Select your region" is hard coded but I would like to parse the following for just the RegionName . 目前,“选择您的区域”是硬编码的,但我想解析以下只为RegionName

import boto3

ec2 = boto3.client('ec2')
regions = ec2.describe_regions()
print(regions)

My output is JSON like so: 我的输出是JSON,如下所示:

{'Regions': [{'Endpoint': 'ec2.ap-south-1.amazonaws.com', 'RegionName': 'ap-south-1'}, {'Endpoint': 'ec2.eu-west-1.amazonaws.com', 'RegionName': 'eu-west-1'}, {'Endpoint': 'ec2.ap-southeast-1.amazonaws.com', 'RegionName': 'ap-southeast-1'}]} {'Regions':[{'Endpoint':'ec2.ap-south-1.amazonaws.com','RegionName':'ap-south-1'},{'Endpoint':'ec2.eu-west- 1.amazonaws.com','RegionName':'eu-west-1'},{'Endpoint':'ec2.ap-southeast-1.amazonaws.com','RegionName':'ap-southeast-1' }]}

I've trimmed off the repeating data and the ResponseMetadata for the sake of space. 为了空间,我已经删除了重复数据和ResponseMetadata。

How can I parse the RegionName into a list? 如何将RegionName解析为列表?

In addition to Frédéric's answer, you can also get known regions for each service without making any service calls. 除了Frédéric的答案,您还可以在不进行任何服务呼叫的情况下获取每项服务的已知区域。 I will caution you, however, that since this is pulling from botocore's local models rather than hitting an endpoint, it will not always be exhaustive since you need to update botocore to update the list. 但是,我会提醒您,因为这是从botocore的本地模型中提取而不是命中端点,所以它并不总是详尽无遗,因为您需要更新botocore来更新列表。

from boto3.session import Session

s = Session()
dynamodb_regions = s.get_available_regions('dynamodb')

Additionally, you are not restricted to the regions in this list. 此外,您不限于此列表中的区域。 If you are using an older version of botocore you can still use new regions by specifying them. 如果您使用的是旧版本的botocore,则仍可以通过指定它们来使用新区域。 They just won't appear in this list. 它们不会出现在此列表中。

The following will return you the RegionName and Endpoint for each region. 以下内容将返回每个区域的RegionName和Endpoint。

# List all regions
client = boto3.client('ec2')
regions = [region['RegionName'] for region in client.describe_regions()['Regions']]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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