@@ -156,6 +156,7 @@ def get(
156156 recursive = False ,
157157 retry_count = 5 ,
158158 headers = None ,
159+ return_none_for_not_found_error = False ,
159160):
160161 """Fetch a resource from the metadata server.
161162
@@ -173,6 +174,8 @@ def get(
173174 retry_count (int): How many times to attempt connecting to metadata
174175 server using above timeout.
175176 headers (Optional[Mapping[str, str]]): Headers for the request.
177+ return_none_for_not_found_error (Optional[bool]): If True, returns None
178+ for 404 error instead of throwing an exception.
176179
177180 Returns:
178181 Union[Mapping, str]: If the metadata server returns JSON, a mapping of
@@ -216,8 +219,17 @@ def get(
216219 "metadata service. Compute Engine Metadata server unavailable" .format (url )
217220 )
218221
222+ content = _helpers .from_bytes (response .data )
223+
224+ if response .status == http_client .NOT_FOUND and return_none_for_not_found_error :
225+ _LOGGER .info (
226+ "Compute Engine Metadata server call to %s returned 404, reason: %s" ,
227+ path ,
228+ content ,
229+ )
230+ return None
231+
219232 if response .status == http_client .OK :
220- content = _helpers .from_bytes (response .data )
221233 if (
222234 _helpers .parse_content_type (response .headers ["content-type" ])
223235 == "application/json"
@@ -232,14 +244,14 @@ def get(
232244 raise new_exc from caught_exc
233245 else :
234246 return content
235- else :
236- raise exceptions .TransportError (
237- "Failed to retrieve {} from the Google Compute Engine "
238- "metadata service. Status: {} Response:\n {}" .format (
239- url , response .status , response .data
240- ),
241- response ,
242- )
247+
248+ raise exceptions .TransportError (
249+ "Failed to retrieve {} from the Google Compute Engine "
250+ "metadata service. Status: {} Response:\n {}" .format (
251+ url , response .status , response .data
252+ ),
253+ response ,
254+ )
243255
244256
245257def get_project_id (request ):
@@ -259,6 +271,29 @@ def get_project_id(request):
259271 return get (request , "project/project-id" )
260272
261273
274+ def get_universe_domain (request ):
275+ """Get the universe domain value from the metadata server.
276+
277+ Args:
278+ request (google.auth.transport.Request): A callable used to make
279+ HTTP requests.
280+
281+ Returns:
282+ str: The universe domain value. If the universe domain endpoint is not
283+ not found, return the default value, which is googleapis.com
284+
285+ Raises:
286+ google.auth.exceptions.TransportError: if an error other than
287+ 404 occurs while retrieving metadata.
288+ """
289+ universe_domain = get (
290+ request , "universe/universe_domain" , return_none_for_not_found_error = True
291+ )
292+ if not universe_domain :
293+ return "googleapis.com"
294+ return universe_domain
295+
296+
262297def get_service_account_info (request , service_account = "default" ):
263298 """Get information about a service account from the metadata server.
264299
0 commit comments