boa*_*der 4 amazon-web-services boto3
现在是否boto3可以将AWS区域代码转换为AWS区域名称,例如转换('us-west-1', 'us-east-1', 'us-west-2')为('N. California', 'N. Virginia', 'Oregon')?
我可以使用以下代码段获取AWS区域代码列表:
from boto3.session import Session
s = Session()
regions = s.get_available_regions('rds')
print("regions:", regions)
$ python3 regions.py
regions: ['ap-northeast-1', 'ap-northeast-2', 'ap-south-1', 'ap-southeast-1', 'ap-southeast-2', 'ca-central-1', 'eu-central-1', 'eu-west-1', 'eu-west-2', 'eu-west-3', 'sa-east-1', 'us-east-1', 'us-east-2', 'us-west-1', 'us-west-2']
Run Code Online (Sandbox Code Playgroud)
是否有等效的代码段可以给我AWS区域名称?
AWS刚刚发布了一项功能,该功能允许使用AWS Systems Manager参数存储查询AWS区域,端点等。
使用和功能boto3,您可以执行以下操作:
import boto3
client = boto3.client('ssm')
response = client.get_parameter(
Name='/aws/service/global-infrastructure/regions/us-west-1/longName'
)
region_name = response['Parameter']['Value'] # US West (N. California)
Run Code Online (Sandbox Code Playgroud)
要获取所有可用区域,您可以首先使用get_parameters_by_path()以下路径使用/aws/service/global-infrastructure/regions。
注意:即使这是公共数据,也需要适当的IAM权限。
编辑:正如 @jogold 所提到的,随着最近推出了 Query for AWS Systems Manager Parameter Store,我建议使用它直接从 AWS 进行查询,而不是在我的答案中使用自定义脚本。
\n\n根据boto3 文档,没有用于描述区域的通俗名称的本机功能。
这是一个带有函数 的小脚本convertRegionCodesToNames(),它获取有效区域 ID 的列表并将它们转换为通用名称。根据需要添加错误处理,以处理无效输入、零长度数组或boto3.
# replace `regions` variable with the output from the get_available_instances() response\n\nregions = [\'ap-northeast-1\', \'ap-northeast-2\', \'ap-south-1\', \'ap-southeast-1\', \'ap-southeast-2\', \'ca-central-1\', \'eu-central-1\', \'eu-west-1\', \'eu-west-2\', \'eu-west-3\', \'sa-east-1\', \'us-east-1\', \'us-east-2\', \'us-west-1\', \'us-west-2\']\n\ndef convertRegionCodesToNames(regions):\n # static dict of all region key-value pairs\n region_dict = {\n "us-east-1": "N. Virginia",\n "us-east-2": "Ohio",\n "us-west-1": "N. California",\n "us-west-2": "Oregon",\n "ca-central-1": "Central",\n "eu-west-1": "Ireland",\n "eu-central-1": "Frankfurt",\n "eu-west-2": "London",\n "eu-west-3": "Paris",\n "eu-north-1": "Stockholm",\n "ap-northeast-1": "Tokyo",\n "ap-northeast-2": "Seoul",\n "ap-southeast-1": "Singapore",\n "ap-southeast-2": "Sydney",\n "ap-south-1": "Mumbai",\n "sa-east-1": "S\xc3\xa3o Paulo",\n "us-gov-west-1": "US Gov West 1",\n "us-gov-east-1": "US Gov East 1"\n } \n\n for i in range(len(regions)):\n regions[i] = region_dict[regions[i]]\n\n return regions\n\nconverted_regions = convertRegionCodesToNames(regions)\nprint("regions:", converted_regions) \nRun Code Online (Sandbox Code Playgroud)\n\n添加后运行$ python3 regions.py会输出:
regions: [\'Tokyo\', \'Seoul\', \'Mumbai\', \'Singapore\', \'Sydney\', \'Central\', \'Frankfurt\', \'Ireland\', \'London\', \'Paris\', \'S\xc3\xa3o Paulo\', \'N. Virginia\', \'Ohio\', \'N. California\', \'Oregon\']\nRun Code Online (Sandbox Code Playgroud)\n
| 归档时间: |
|
| 查看次数: |
941 次 |
| 最近记录: |