Coverage for /pythoncovmergedfiles/medio/medio/usr/local/lib/python3.8/site-packages/msal/region.py: 26%

19 statements  

« prev     ^ index     » next       coverage.py v7.2.7, created at 2023-06-07 06:20 +0000

1import os 

2import logging 

3 

4logger = logging.getLogger(__name__) 

5 

6 

7def _detect_region(http_client=None): 

8 region = os.environ.get("REGION_NAME", "").replace(" ", "").lower() # e.g. westus2 

9 if region: 

10 return region 

11 if http_client: 

12 return _detect_region_of_azure_vm(http_client) # It could hang for minutes 

13 return None 

14 

15 

16def _detect_region_of_azure_vm(http_client): 

17 url = ( 

18 "http://169.254.169.254/metadata/instance" 

19 

20 # Utilize the "route parameters" feature to obtain region as a string 

21 # https://docs.microsoft.com/en-us/azure/virtual-machines/windows/instance-metadata-service?tabs=linux#route-parameters 

22 "/compute/location?format=text" 

23 

24 # Location info is available since API version 2017-04-02 

25 # https://docs.microsoft.com/en-us/azure/virtual-machines/windows/instance-metadata-service?tabs=linux#response-1 

26 "&api-version=2021-01-01" 

27 ) 

28 logger.info( 

29 "Connecting to IMDS {}. " 

30 "It may take a while if you are running outside of Azure. " 

31 "You should consider opting in/out region behavior on-demand, " 

32 'by loading a boolean flag "is_deployed_in_azure" ' 

33 'from your per-deployment config and then do ' 

34 '"app = ConfidentialClientApplication(..., ' 

35 'azure_region=is_deployed_in_azure)"'.format(url)) 

36 try: 

37 # https://docs.microsoft.com/en-us/azure/virtual-machines/windows/instance-metadata-service?tabs=linux#instance-metadata 

38 resp = http_client.get(url, headers={"Metadata": "true"}) 

39 except: 

40 logger.info( 

41 "IMDS {} unavailable. Perhaps not running in Azure VM?".format(url)) 

42 return None 

43 else: 

44 return resp.text.strip() 

45