Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions google/auth/compute_engine/_metadata.py
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,10 @@
except ValueError: # pragma: NO COVER
_METADATA_DEFAULT_TIMEOUT = 3

# This is used to disable checking for the GCE metadata server and directly
# assuming it's not available.
_NO_GCE_CHECK = os.getenv(environment_vars.NO_GCE_CHECK) == "true"

# Detect GCE Residency
_GOOGLE = "Google"
_GCE_PRODUCT_NAME_FILE = "/sys/class/dmi/id/product_name"
Expand All @@ -75,6 +79,9 @@ def is_on_gce(request):
Returns:
bool: True if the code runs on Google Compute Engine, False otherwise.
"""
if _NO_GCE_CHECK:
return False

if ping(request):
return True

Expand Down
6 changes: 6 additions & 0 deletions google/auth/environment_vars.py
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,12 @@
"""Environment variable providing an alternate ip:port to be used for ip-only
GCE metadata requests."""

NO_GCE_CHECK = "NO_GCE_CHECK"
"""Environment variable controlling whether to check if running on GCE or not.

The default value is false. Users have to explicitly set this value to true
in order to disable the GCE check."""

GOOGLE_API_USE_CLIENT_CERTIFICATE = "GOOGLE_API_USE_CLIENT_CERTIFICATE"
"""Environment variable controlling whether to use client certificate or not.

Expand Down
14 changes: 14 additions & 0 deletions tests/compute_engine/test__metadata.py
Original file line number Diff line number Diff line change
Expand Up @@ -83,6 +83,20 @@ def test_is_on_gce_ping_success():
assert _metadata.is_on_gce(request)


def test_is_on_gce_no_gce_check():
request = make_request("", headers=_metadata._METADATA_HEADERS)

os.environ[environment_vars.NO_GCE_CHECK] = "true"
importlib.reload(_metadata)

try:
assert not _metadata.is_on_gce(request)
assert request.call_count == 0
finally:
del os.environ[environment_vars.NO_GCE_CHECK]
importlib.reload(_metadata)


@mock.patch("os.name", new="nt")
def test_is_on_gce_windows_success():
request = make_request("", headers={_metadata._METADATA_FLAVOR_HEADER: "meep"})
Expand Down