Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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. Currently, the "Select your region" is hard coded but I would like to parse the following for just the RegionName.

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

My output is JSON like so:

{'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.

How can I parse the RegionName into a list?

like image 625
Shawn Avatar asked Jul 19 '16 06:07

Shawn


People also ask

What is Boto3 session ()?

The boto3. Session class, according to the docs, “ stores configuration state and allows you to create service clients and resources.” Most importantly it represents the configuration of an IAM identity (IAM user or assumed role) and AWS region, the two things you need to talk to an AWS service.

What is Boto3 reservation?

From the boto docs: A reservation corresponds to a command to start instances. You can see what instances are associated with a reservation: >>> instances = reservations[0].instances >>> instances [Instance:i-00000000]


2 Answers

In addition to Frédéric's answer, you can also get known regions for each service without making any service calls. 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.

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. They just won't appear in this list.

like image 96
Jordon Phillips Avatar answered Sep 23 '22 11:09

Jordon Phillips


The following will return you the RegionName and Endpoint for each region.

# List all regions client = boto3.client('ec2') regions = [region['RegionName'] for region in client.describe_regions()['Regions']] 
like image 45
Frederic Henri Avatar answered Sep 23 '22 11:09

Frederic Henri