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 with support for multiple AWS profiles .
33
4- It includes the following capabilities :
4+ Capabilities :
55 - Fetching a list of all AWS regions, with the option to include or exclude regions based on account opt-in status.
66 - Retrieving the geographical location description for a specific AWS region from the AWS Systems Manager (SSM) Parameter Store.
77 - Fetching geographical locations for multiple AWS regions using concurrent threading for improved performance.
88 - Applying include and exclude filters to the list of regions to customize the output.
99 - Generating a comprehensive list of AWS regions, with optional detailed information about each region.
10+ - Utilizing different AWS profiles for the retrieval of region information.
1011
1112Functions:
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.
13+ - get_region_list: Main function to retrieve a list of AWS regions, optionally filtering by include and exclude lists,
14+ and returning detailed information if required.
1415
15- Private Functions:
16+ Private Functions:
1617 - _fetch_all_regions: Retrieves a list of all AWS regions.
1718 - _fetch_region_description: Fetches the geographical location for a specific AWS region.
1819 - _fetch_region_descriptions: Fetches geographical locations for multiple AWS regions using threading.
2425Dependencies:
2526 - boto3: AWS SDK for Python to interact with various AWS services like EC2 and SSM.
2627 - concurrent.futures: Standard library module to enable asynchronous execution using threading.
28+ - botocore.exceptions: Exceptions for handling errors during boto3 operations.
2729
2830Usage:
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.
31+ This module is intended to be used as part of the wolfsoftware.get-aws-regions package.
32+ The main entry point is the `get_region_list` function, which provides flexibility in retrieving
33+ and customizing the list of AWS regions based on user-defined criteria, including the ability
34+ to specify different AWS profiles.
3135"""
36+
3237from typing import Any , List , Dict , Optional , Union
3338
3439from concurrent .futures ._base import Future
3540from concurrent .futures import ThreadPoolExecutor , as_completed
3641
3742import boto3 # pylint: disable=import-error
43+ from botocore .exceptions import BotoCoreError , ClientError
3844
3945from .exceptions import RegionListingError
4046
4147
42- def _fetch_all_regions (all_regions : bool = True ) -> List [Dict [str , Union [str , bool ]]]:
48+ def _fetch_all_regions (all_regions : bool = True , profile_name : Optional [ str ] = None ) -> List [Dict [str , Union [str , bool ]]]:
4349 """
4450 Retrieve a list of all AWS regions.
4551
4652 Arguments:
4753 all_regions (bool): If True, list all available regions, including those not opted into.
4854 If False, list only regions opted into by the account.
55+ profile_name (Optional[str]): The name of the AWS profile to use.
4956
5057 Returns:
5158 List[Dict[str, Union[str, bool]]]: A list of dictionaries containing information about each region.
@@ -54,8 +61,9 @@ def _fetch_all_regions(all_regions: bool = True) -> List[Dict[str, Union[str, bo
5461 RegionListingError: If there is an error in retrieving the regions.
5562 """
5663 try :
57- # Initialize a session using Amazon EC2
58- ec2 : Any = boto3 .client ('ec2' )
64+ # Initialize a session using Amazon EC2 with the specified profile
65+ session = boto3 .Session (profile_name = profile_name ) if profile_name else boto3 .Session ()
66+ ec2 : Any = session .client ('ec2' )
5967
6068 # Retrieve a list of all available regions or only opted-in regions based on the flag
6169 if all_regions :
@@ -71,18 +79,19 @@ def _fetch_all_regions(all_regions: bool = True) -> List[Dict[str, Union[str, bo
7179
7280 return regions
7381
74- except boto3 . exceptions . Boto3Error as e :
82+ except ( BotoCoreError , ClientError ) as e :
7583 raise RegionListingError (f"An error occurred while listing regions: { str (e )} " ) from e
7684 except Exception as e :
7785 raise RegionListingError (f"An unexpected error occurred: { str (e )} " ) from e
7886
7987
80- def _fetch_region_description (region_name : str ) -> Dict [str , str ]:
88+ def _fetch_region_description (region_name : str , profile_name : Optional [ str ] = None ) -> Dict [str , str ]:
8189 """
8290 Fetch the geographical location for a specific AWS region from SSM Parameter Store.
8391
8492 Arguments:
8593 region_name (str): The name of the region to fetch the geographical location for.
94+ profile_name (Optional[str]): The name of the AWS profile to use.
8695
8796 Returns:
8897 Dict[str, str]: A dictionary containing the region name and its geographical location.
@@ -91,27 +100,29 @@ def _fetch_region_description(region_name: str) -> Dict[str, str]:
91100 RegionListingError: If there is an error in retrieving the region geographical location.
92101 """
93102 try :
94- # Initialize a session using Amazon SSM
95- ssm : Any = boto3 .client ('ssm' )
103+ # Initialize a session using Amazon SSM with the specified profile
104+ session = boto3 .Session (profile_name = profile_name ) if profile_name else boto3 .Session ()
105+ ssm : Any = session .client ('ssm' )
96106
97107 # Retrieve the parameter for the region description
98108 parameter_name : str = f"/aws/service/global-infrastructure/regions/{ region_name } /longName"
99109 response : Any = ssm .get_parameter (Name = parameter_name )
100110
101111 return {region_name : response ['Parameter' ]['Value' ]}
102112
103- except boto3 . exceptions . Boto3Error as e :
113+ except ( BotoCoreError , ClientError ) as e :
104114 raise RegionListingError (f"An error occurred while retrieving geographical location for region { region_name } : { str (e )} " ) from e
105115 except Exception as e :
106116 raise RegionListingError (f"An unexpected error occurred: { str (e )} " ) from e
107117
108118
109- def _fetch_region_descriptions (region_names : List [str ]) -> Dict [str , str ]:
119+ def _fetch_region_descriptions (region_names : List [str ], profile_name : Optional [ str ] = None ) -> Dict [str , str ]:
110120 """
111121 Fetch geographical locations for multiple AWS regions from SSM Parameter Store using threading for better performance.
112122
113123 Arguments:
114124 region_names (List[str]): A list of region names to fetch geographical locations for.
125+ profile_name (Optional[str]): The name of the AWS profile to use.
115126
116127 Returns:
117128 Dict[str, str]: A dictionary mapping region codes to their geographical locations.
@@ -122,7 +133,10 @@ def _fetch_region_descriptions(region_names: List[str]) -> Dict[str, str]:
122133 descriptions : Dict = {}
123134
124135 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 }
136+ future_to_region : Dict [Future [Dict [str , str ]], str ] = {
137+ executor .submit (_fetch_region_description , region , profile_name ): region
138+ for region in region_names
139+ }
126140
127141 for future in as_completed (future_to_region ):
128142 region : str = future_to_region [future ]
@@ -166,8 +180,9 @@ def _apply_region_filters(
166180def get_region_list (
167181 include_list : Optional [List [str ]] = None ,
168182 exclude_list : Optional [List [str ]] = None ,
169- all_regions : bool = True ,
170- details : bool = False
183+ all_regions : Optional [bool ] = True ,
184+ details : Optional [bool ] = False ,
185+ profile_name : Optional [str ] = None
171186) -> Union [List [Dict [str , Union [str , bool ]]], List [str ]]:
172187 """
173188 Retrieve a list of AWS regions, optionally filtering by include and exclude lists.
@@ -179,6 +194,7 @@ def get_region_list(
179194 exclude_list (Optional[List[str]]): A list of regions to exclude. These regions will be omitted from the returned list if specified.
180195 all_regions (bool): If True, list all available regions, including those not opted into. If False, list only regions opted into by the account.
181196 details (bool): If True, return detailed information about each region. If False, return only the region names.
197+ profile_name (Optional[str]): The name of the AWS profile to use.
182198
183199 Returns:
184200 Union[List[Dict[str, Union[str, bool]]], List[str]]: A sorted list of regions with detailed information or just the region names.
@@ -187,15 +203,15 @@ def get_region_list(
187203 RegionListingError: If there is an error in retrieving the regions.
188204 """
189205 try :
190- all_regions_list : List [Dict [str , str | bool ]] = _fetch_all_regions (all_regions )
206+ all_regions_list : List [Dict [str , str | bool ]] = _fetch_all_regions (all_regions , profile_name )
191207 except Exception as e :
192208 raise RegionListingError (f"An error occurred while retrieving regions: { str (e )} " ) from e
193209
194210 filtered_regions : List [Dict [str , str | bool ]] = _apply_region_filters (all_regions_list , include_list , exclude_list )
195211
196212 if details :
197213 region_names : List [str | bool ] = [region ['RegionName' ] for region in filtered_regions ]
198- region_descriptions : Dict [str , str ] = _fetch_region_descriptions (region_names )
214+ region_descriptions : Dict [str , str ] = _fetch_region_descriptions (region_names , profile_name )
199215 for region in filtered_regions :
200216 region ['GeographicalLocation' ] = region_descriptions .get (region ['RegionName' ], "Unknown" )
201217 print ("Filtered Regions with Details:" , filtered_regions ) # Debug print
0 commit comments