随着 AWS 扩展并添加新区域,我希望我的代码能够自动检测到这一点。目前,“选择您的区域”是硬编码的,但我想仅解析以下内容以获取 RegionName。
import boto3
ec2 = boto3.client('ec2')
regions = ec2.describe_regions()
print(regions)
我的输出是 JSON,如下所示:
{'区域':[{'端点':'ec2.ap-south-1.amazonaws.com','RegionName':'ap-south-1'},{'端点':'ec2.eu-west -1.amazonaws.com', 'RegionName': 'eu-west-1'}, {'Endpoint': 'ec2.ap-southeast-1.amazonaws.com', 'RegionName': 'ap-southeast-1 '}]}
为了节省空间,我删除了重复数据和响应元数据。
如何将 RegionName 解析为列表?
除了 Frédéric 的回答之外,您还可以获取每个服务的已知区域,而无需拨打任何服务电话。不过,我要提醒您,由于这是从 botocore 的本地模型中提取而不是到达端点,因此它并不总是详尽的,因为您需要更新 botocore 来更新列表。
from boto3.session import Session
s = Session()
dynamodb_regions = s.get_available_regions('dynamodb')
此外,您不限于此列表中的区域。如果您使用的是旧版本的 botocore,您仍然可以通过指定新区域来使用它们。他们只是不会出现在这个列表中。
以下内容将返回每个区域的 RegionName 和 Endpoint。
# List all regions
client = boto3.client('ec2')
regions = [region['RegionName'] for region in client.describe_regions()['Regions']]
您可能需要一个可用的区域列表,您可以使用它来执行更多操作。
boto3.session.Session()
返回的区域列表只是部分答案,因为通常返回的某些区域在给定的 AWS 账户中被禁用。
要获取可用的区域列表,请对每个区域进行简单的测试调用以查看其是否已启用。
下面的代码被设计为在帐户中的启用区域上循环。这些函数接受可选的
Credentials
参数,例如 boto3 sts Should_role 返回的类型。
此方法的缺点是获取 AWS 账户中的区域列表通常需要大约 20 秒。尽管这对于您的场景来说可能是可以接受的。
import boto3
# Constants
empty_credentials = {"AccessKeyId":None, "SecretAccessKey":None, "SessionToken":None}
def get_enabled_regions(Credentials=empty_credentials):
# Get available regions from boto3 sessions
available_regions = boto3.session.Session().get_available_regions('ec2')
enabled_regions = []
for region in available_regions:
try:
# For each available region, do one small test call using an ec2 client.
ec2_client = get_service_client("ec2", Credentials=Credentials, region=region)
ec2_client.describe_vpcs(MaxResults=5)
# If the call succeeds, the region is enabled, so add to enabled_regions list.
enabled_regions.append(region)
except Exception as e:
# If there is an exception, it means the region is disabled in this account.
continue
return enabled_regions
def get_service_client(service, region=None, config=None, Credentials=empty_credentials):
return boto3.client(service, region_name=region, config=config, aws_access_key_id=Credentials["AccessKeyId"],aws_secret_access_key=Credentials["SecretAccessKey"],aws_session_token=Credentials["SessionToken"])
regions = get_enabled_regions()
for region in regions:
# Get a region specific client.
ec2_client = get_service_client("ec2", region=region)
# Do region specific stuff here. Don't forget to paginate or use NextTokens.
print(ec2_client.describe_volumes())
或者,您也可以尝试这些其他方法。
RegionOptStatusContains
。但根据我的经验,无论您提供什么过滤器,返回的列表都可能包含禁用区域。