Introduction
AWS Regions allow users to deploy applications closer to their customers. Sometimes, it’s important to dynamically determine which AWS regions are activated in an account. This blog demonstrates how to use an AWS Lambda function with Boto3 to list all activated AWS regions.
Overview
The Lambda function performs the following actions:
- Connects to the AWS EC2 service.
- Calls the
describe_regionsAPI to fetch all AWS regions. - Filters for regions that are activated (opted-in or do not require opt-in).
Prerequisites
- IAM Role: The Lambda function must have permissions to call
ec2:DescribeRegions. - Boto3: AWS SDK for Python is required to interact with AWS services.
Lambda Function Code
import boto3
import json
def get_activated_regions(ec2_client):
"""Get all activated AWS regions for the assumed role."""
try:
# Retrieve all regions
response = ec2_client.describe_regions(AllRegions=True)
all_regions = response["Regions"]
# Filter for regions that are currently enabled
activated_regions = [region["RegionName"] for region in all_regions if region["OptInStatus"] == "opt-in-not-required" or region["OptInStatus"] == "opted-in"]
return activated_regions
except Exception as e:
print(f"Error fetching regions: {e}")
return []
def lambda_handler(event, context):
"""Lambda handler function."""
try:
# Create an EC2 client
ec2_client = boto3.client('ec2')
# Get activated AWS regions
activated_regions = get_activated_regions(ec2_client)
print(f"Activated regions: {activated_regions}")
return {
'statusCode': 200,
'body': json.dumps({
'message': 'Successfully retrieved activated regions.',
'regions': activated_regions
})
}
except Exception as e:
print(f"Error in lambda_handler: {e}")
return {
'statusCode': 500,
'body': json.dumps({
'message': 'Error retrieving activated regions.',
'error': str(e)
})
}Key Concepts
- Activated Regions: AWS regions that are either automatically enabled or have been opted-in manually.
- EC2 describe_regions API: This API call returns the list of AWS regions with their opt-in status.
- Boto3: AWS SDK for Python, which is used to interact with AWS services from the Lambda function.
How to Deploy
- Create Lambda Function
Open AWS Lambda and create a new function.
Copy and paste the code provided above. - IAM Role
Attach a policy to the Lambda’s execution role with permission forec2:DescribeRegions. - Test the Function
Run a test event in the Lambda console to verify that the list of activated regions is returned.
Possible Enhancements
- Logging and Monitoring: Add logging to AWS CloudWatch for better debugging.
- Custom Alerts: Use AWS SNS to send notifications if the Lambda encounters any errors.
Conclusion
This Lambda function dynamically retrieves all activated AWS regions, which can be useful for compliance, resource deployment, and auditing purposes. By using this automated approach, you can save time and maintain accuracy in managing your AWS infrastructure.







