codekingpro/portable-devtools
114k
1import os2import logging3 4logger = logging.getLogger(__name__)5 6 7def _detect_region(http_client=None):8 region = os.environ.get("REGION_NAME", "").replace(" ", "").lower() # e.g. westus29 if region:10 return region11 if http_client:12 return _detect_region_of_azure_vm(http_client) # It could hang for minutes13 return None14 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 string21 # https://docs.microsoft.com/en-us/azure/virtual-machines/windows/instance-metadata-service?tabs=linux#route-parameters22 "/compute/location?format=text"23 24 # Location info is available since API version 2017-04-0225 # https://docs.microsoft.com/en-us/azure/virtual-machines/windows/instance-metadata-service?tabs=linux#response-126 "&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-metadata38 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 None43 else:44 return resp.text.strip()45 46 