11"""
2- This module provides functionalities for retrieving and processing AWS region information.
2+ This module provides functionalities for retrieving and processing AWS region information
3+ with support for multiple AWS profiles.
34
4- It includes the following capabilities :
5+ Capabilities :
56 - Fetching a list of all AWS regions, with the option to include or exclude regions based on account opt-in status.
67 - Retrieving the geographical location description for a specific AWS region from the AWS Systems Manager (SSM) Parameter Store.
78 - Fetching geographical locations for multiple AWS regions using concurrent threading for improved performance.
89 - Applying include and exclude filters to the list of regions to customize the output.
910 - Generating a comprehensive list of AWS regions, with optional detailed information about each region.
11+ - Utilizing different AWS profiles for the retrieval of region information.
1012
1113Functions:
12- - get_region_list: Main function to retrieve a list of AWS regions, optionally filtering by include and exclude lists and returning
13- detailed information if required.
14+ - get_region_list: Main function to retrieve a list of AWS regions, optionally filtering by include and exclude lists,
15+ and returning detailed information if required.
1416
15- Private Functions:
17+ Private Functions:
1618 - _fetch_all_regions: Retrieves a list of all AWS regions.
1719 - _fetch_region_description: Fetches the geographical location for a specific AWS region.
1820 - _fetch_region_descriptions: Fetches geographical locations for multiple AWS regions using threading.
2426Dependencies:
2527 - boto3: AWS SDK for Python to interact with various AWS services like EC2 and SSM.
2628 - concurrent.futures: Standard library module to enable asynchronous execution using threading.
29+ - botocore.exceptions: Exceptions for handling errors during boto3 operations.
2730
2831Usage:
29- This module is intended to be used as part of the wolfsoftware.get-aws-regions package. The main entry point is the `get_region_list` function,
30- which provides flexibility in retrieving and customizing the list of AWS regions based on user-defined criteria.
32+ This module is intended to be used as part of the wolfsoftware.get-aws-regions package.
33+ The main entry point is the `get_region_list` function, which provides flexibility in retrieving
34+ and customizing the list of AWS regions based on user-defined criteria, including the ability
35+ to specify different AWS profiles.
3136"""
37+
3238from typing import Any , List , Dict , Optional , Union
3339
3440from concurrent .futures ._base import Future
3541from concurrent .futures import ThreadPoolExecutor , as_completed
3642
3743import boto3 # pylint: disable=import-error
44+ from botocore .exceptions import BotoCoreError , ClientError
3845
3946from .exceptions import RegionListingError
4047
4148
42- def _fetch_all_regions (all_regions : bool = True ) -> List [Dict [str , Union [str , bool ]]]:
49+ def _fetch_all_regions (all_regions : bool = True , profile_name : Optional [ str ] = None ) -> List [Dict [str , Union [str , bool ]]]:
4350 """
4451 Retrieve a list of all AWS regions.
4552
4653 Arguments:
4754 all_regions (bool): If True, list all available regions, including those not opted into.
4855 If False, list only regions opted into by the account.
56+ profile_name (Optional[str]): The name of the AWS profile to use.
4957
5058 Returns:
5159 List[Dict[str, Union[str, bool]]]: A list of dictionaries containing information about each region.
@@ -54,8 +62,9 @@ def _fetch_all_regions(all_regions: bool = True) -> List[Dict[str, Union[str, bo
5462 RegionListingError: If there is an error in retrieving the regions.
5563 """
5664 try :
57- # Initialize a session using Amazon EC2
58- ec2 : Any = boto3 .client ('ec2' )
65+ # Initialize a session using Amazon EC2 with the specified profile
66+ session = boto3 .Session (profile_name = profile_name ) if profile_name else boto3 .Session ()
67+ ec2 : Any = session .client ('ec2' )
5968
6069 # Retrieve a list of all available regions or only opted-in regions based on the flag
6170 if all_regions :
@@ -71,18 +80,19 @@ def _fetch_all_regions(all_regions: bool = True) -> List[Dict[str, Union[str, bo
7180
7281 return regions
7382
74- except boto3 . exceptions . Boto3Error as e :
83+ except ( BotoCoreError , ClientError ) as e :
7584 raise RegionListingError (f"An error occurred while listing regions: { str (e )} " ) from e
7685 except Exception as e :
7786 raise RegionListingError (f"An unexpected error occurred: { str (e )} " ) from e
7887
7988
80- def _fetch_region_description (region_name : str ) -> Dict [str , str ]:
89+ def _fetch_region_description (region_name : str , profile_name : Optional [ str ] = None ) -> Dict [str , str ]:
8190 """
8291 Fetch the geographical location for a specific AWS region from SSM Parameter Store.
8392
8493 Arguments:
8594 region_name (str): The name of the region to fetch the geographical location for.
95+ profile_name (Optional[str]): The name of the AWS profile to use.
8696
8797 Returns:
8898 Dict[str, str]: A dictionary containing the region name and its geographical location.
@@ -91,27 +101,29 @@ def _fetch_region_description(region_name: str) -> Dict[str, str]:
91101 RegionListingError: If there is an error in retrieving the region geographical location.
92102 """
93103 try :
94- # Initialize a session using Amazon SSM
95- ssm : Any = boto3 .client ('ssm' )
104+ # Initialize a session using Amazon SSM with the specified profile
105+ session = boto3 .Session (profile_name = profile_name ) if profile_name else boto3 .Session ()
106+ ssm : Any = session .client ('ssm' )
96107
97108 # Retrieve the parameter for the region description
98109 parameter_name : str = f"/aws/service/global-infrastructure/regions/{ region_name } /longName"
99110 response : Any = ssm .get_parameter (Name = parameter_name )
100111
101112 return {region_name : response ['Parameter' ]['Value' ]}
102113
103- except boto3 . exceptions . Boto3Error as e :
114+ except ( BotoCoreError , ClientError ) as e :
104115 raise RegionListingError (f"An error occurred while retrieving geographical location for region { region_name } : { str (e )} " ) from e
105116 except Exception as e :
106117 raise RegionListingError (f"An unexpected error occurred: { str (e )} " ) from e
107118
108119
109- def _fetch_region_descriptions (region_names : List [str ]) -> Dict [str , str ]:
120+ def _fetch_region_descriptions (region_names : List [str ], profile_name : Optional [ str ] = None ) -> Dict [str , str ]:
110121 """
111122 Fetch geographical locations for multiple AWS regions from SSM Parameter Store using threading for better performance.
112123
113124 Arguments:
114125 region_names (List[str]): A list of region names to fetch geographical locations for.
126+ profile_name (Optional[str]): The name of the AWS profile to use.
115127
116128 Returns:
117129 Dict[str, str]: A dictionary mapping region codes to their geographical locations.
@@ -122,7 +134,7 @@ def _fetch_region_descriptions(region_names: List[str]) -> Dict[str, str]:
122134 descriptions : Dict = {}
123135
124136 with ThreadPoolExecutor () as executor :
125- future_to_region : Dict [Future [Dict [str , str ]], str ] = {executor .submit (_fetch_region_description , region ): region for region in region_names }
137+ future_to_region : Dict [Future [Dict [str , str ]], str ] = {executor .submit (_fetch_region_description , region , profile_name ): region for region in region_names }
126138
127139 for future in as_completed (future_to_region ):
128140 region : str = future_to_region [future ]
@@ -166,8 +178,9 @@ def _apply_region_filters(
166178def get_region_list (
167179 include_list : Optional [List [str ]] = None ,
168180 exclude_list : Optional [List [str ]] = None ,
169- all_regions : bool = True ,
170- details : bool = False
181+ all_regions : Optional [bool ] = True ,
182+ details : Optional [bool ] = False ,
183+ profile_name : Optional [str ] = None
171184) -> Union [List [Dict [str , Union [str , bool ]]], List [str ]]:
172185 """
173186 Retrieve a list of AWS regions, optionally filtering by include and exclude lists.
@@ -179,6 +192,7 @@ def get_region_list(
179192 exclude_list (Optional[List[str]]): A list of regions to exclude. These regions will be omitted from the returned list if specified.
180193 all_regions (bool): If True, list all available regions, including those not opted into. If False, list only regions opted into by the account.
181194 details (bool): If True, return detailed information about each region. If False, return only the region names.
195+ profile_name (Optional[str]): The name of the AWS profile to use.
182196
183197 Returns:
184198 Union[List[Dict[str, Union[str, bool]]], List[str]]: A sorted list of regions with detailed information or just the region names.
@@ -187,15 +201,15 @@ def get_region_list(
187201 RegionListingError: If there is an error in retrieving the regions.
188202 """
189203 try :
190- all_regions_list : List [Dict [str , str | bool ]] = _fetch_all_regions (all_regions )
204+ all_regions_list : List [Dict [str , str | bool ]] = _fetch_all_regions (all_regions , profile_name )
191205 except Exception as e :
192206 raise RegionListingError (f"An error occurred while retrieving regions: { str (e )} " ) from e
193207
194208 filtered_regions : List [Dict [str , str | bool ]] = _apply_region_filters (all_regions_list , include_list , exclude_list )
195209
196210 if details :
197211 region_names : List [str | bool ] = [region ['RegionName' ] for region in filtered_regions ]
198- region_descriptions : Dict [str , str ] = _fetch_region_descriptions (region_names )
212+ region_descriptions : Dict [str , str ] = _fetch_region_descriptions (region_names , profile_name )
199213 for region in filtered_regions :
200214 region ['GeographicalLocation' ] = region_descriptions .get (region ['RegionName' ], "Unknown" )
201215 print ("Filtered Regions with Details:" , filtered_regions ) # Debug print
0 commit comments