AWS
Boto3
Python
Cloud Computing
Regions

How to list available regions with Boto3 Python

Master System Design with Codemia

Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.

Introduction

Listing AWS regions with Boto3 is a common step in deployment and auditing automation. The tricky part is that region availability differs by service, partition, and account policy. A robust approach discovers regions dynamically per service and then filters by organization constraints.

Discover Regions for a Service

Boto3 exposes service specific region discovery through Session.get_available_regions.

python
1import boto3
2
3session = boto3.session.Session()
4regions = session.get_available_regions("ec2")
5
6for region in regions:
7    print(region)

This gives known EC2 regions for the session partition context. It does not guarantee every region is enabled for your account.

Compare Region Coverage Across Services

If your automation depends on multiple services, compare their region sets.

python
1import boto3
2
3session = boto3.session.Session()
4services = ["ec2", "lambda", "s3"]
5
6region_sets = {svc: set(session.get_available_regions(svc)) for svc in services}
7common = sorted(set.intersection(*region_sets.values()))
8
9print("common regions:", common)

This prevents selecting regions where one required service is unavailable.

Handle Profiles and Partitions Explicitly

Different AWS profiles may map to different accounts and permissions. Also, commercial, GovCloud, and China partitions have different region catalogs.

python
session = boto3.session.Session(profile_name="default")
print(session.get_available_regions("ec2"))

Document partition assumptions in your scripts. Silent partition mismatch can produce confusing region lists.

Verify Region Usability with Credential Probe

A region may exist but still be unusable for your account due to policy restrictions. Add lightweight API probes for critical workflows.

python
1import boto3
2from botocore.exceptions import ClientError
3
4session = boto3.session.Session(profile_name="default")
5usable = []
6
7for region in session.get_available_regions("ec2"):
8    sts = session.client("sts", region_name=region)
9    try:
10        sts.get_caller_identity()
11        usable.append(region)
12    except ClientError:
13        pass
14
15print("usable regions:", usable)

For strict automation, fail early when no usable region is found.

Build a Reusable Discovery Helper

Encapsulate region discovery and filtering in one function so every script follows the same logic.

python
1import boto3
2
3
4def discover_regions(service, profile=None, allowlist=None):
5    session = boto3.session.Session(profile_name=profile)
6    regions = set(session.get_available_regions(service))
7    if allowlist:
8        regions = regions.intersection(set(allowlist))
9    return sorted(regions)
10
11
12if __name__ == "__main__":
13    print(discover_regions("ec2", allowlist=["us-east-1", "us-west-2", "eu-west-1"]))

This pattern keeps policy logic centralized and easier to test.

Integrate Region Discovery into Deployment Workflows

Typical production flow:

  1. Discover service regions.
  2. Intersect with policy allowlist.
  3. Probe account usability if needed.
  4. Execute per region jobs.
  5. Record final selected region list in logs.

Persisting final selection helps incident response when policy or AWS availability changes.

Operational Recommendations

  • Cache region discovery results for short durations in long running tools.
  • Recompute periodically to pick up new AWS regions.
  • Avoid hardcoded region lists in repositories unless policy requires strict pinning.
  • Keep profile and partition settings explicit in automation configuration.

These practices reduce surprise failures in multi region operations.

Export Region Inventory for Audits

Security and platform teams often need a saved snapshot of discovered regions. You can export service region inventories to JSON for review.

python
1import json
2import boto3
3
4session = boto3.session.Session(profile_name="default")
5inventory = {
6    "ec2": session.get_available_regions("ec2"),
7    "lambda": session.get_available_regions("lambda"),
8    "s3": session.get_available_regions("s3"),
9}
10
11with open("region_inventory.json", "w", encoding="utf-8") as f:
12    json.dump(inventory, f, indent=2)

Keeping these snapshots in audit artifacts helps explain changes when AWS adds regions or organizational policy updates take effect.

Common Pitfalls

  • Hardcoding one global region list and assuming all services share it.
  • Treating available regions as account enabled regions without probing.
  • Ignoring partition differences across commercial and specialized environments.
  • Forgetting explicit profile selection and using unexpected credentials.
  • Skipping logging of final region set used by deployment jobs.

Summary

  • Discover regions dynamically per service with Boto3 sessions.
  • Compare service footprints when workflows need multiple AWS services.
  • Filter by policy allowlists and probe account usability when needed.
  • Encapsulate discovery logic in reusable helper functions.
  • Log selected regions so operations remain traceable and debuggable.

Course illustration
Course illustration

All Rights Reserved.