@@ -182,15 +182,30 @@ def _is_azure() -> bool:
182182
183183
184184def _get_aws_availability_zone () -> Optional [str ]:
185+ """Get AWS availability zone from EC2 instance metadata.
186+
187+ Uses IMDS (Instance Metadata Service) which is only accessible from within EC2.
188+ Configure via environment variables:
189+ - AWS_EC2_METADATA_SERVICE_ENDPOINT: Override the metadata endpoint
190+ - AWS_EC2_METADATA_DISABLED: Set to 'true' to disable metadata calls
191+ """
185192 if os .environ .get ("AWS_LAMBDA_FUNCTION_NAME" ):
186193 return None
194+
195+ # Respect AWS SDK standard env vars for disabling/configuring metadata
196+ if os .environ .get ("AWS_EC2_METADATA_DISABLED" , "" ).lower () == "true" :
197+ return None
198+
199+ # Use AWS SDK standard endpoint override, or default to standard IMDS address
200+ endpoint = os .environ .get ("AWS_EC2_METADATA_SERVICE_ENDPOINT" , "http://169.254.169.254" )
201+ if not endpoint or not endpoint .startswith (("http://" , "https://" )):
202+ return None
203+
187204 try :
188205 import urllib .request
189206
190- req = urllib .request .Request (
191- "http://169.254.169.254/latest/meta-data/placement/availability-zone" ,
192- headers = {"Accept" : "text/plain" },
193- )
207+ url = f"{ endpoint } /latest/meta-data/placement/availability-zone"
208+ req = urllib .request .Request (url , headers = {"Accept" : "text/plain" }) # noqa: S310
194209 with urllib .request .urlopen (req , timeout = 0.5 ) as resp : # noqa: S310
195210 return resp .read ().decode ("utf-8" ).strip ()
196211 except Exception :
0 commit comments