Allow customizing the GCE metadata service address via an env var. (#704)

The goal here is to make it possible for a user of a binary that depends on
this library (eg the google cloud SDK) to be able to customize where it looks
for the GCE metadata service. (An adventurous user can already customize the
GCE metadata service location via the existing global vars in this library.)

The only bit of awkwardness here is really the test: since this is a top-level
statement, reloading is the only way to ensure it works.
This commit is contained in:
Craig Citro
2017-03-27 09:47:44 -07:00
committed by Jon Wayne Parrott
parent a3cf56b659
commit feec15f070
3 changed files with 22 additions and 2 deletions

View File

@@ -108,7 +108,7 @@ except ValueError: # pragma: NO COVER
GCE_METADATA_TIMEOUT = 3
_SERVER_SOFTWARE = 'SERVER_SOFTWARE'
_GCE_METADATA_URI = 'http://169.254.169.254'
_GCE_METADATA_URI = 'http://' + os.getenv('GCE_METADATA_IP', '169.254.169.254')
_METADATA_FLAVOR_HEADER = 'metadata-flavor' # lowercase header
_DESIRED_METADATA_FLAVOR = 'Google'
_GCE_HEADERS = {_METADATA_FLAVOR_HEADER: _DESIRED_METADATA_FLAVOR}

View File

@@ -19,6 +19,7 @@ See https://cloud.google.com/compute/docs/metadata
import datetime
import json
import os
from six.moves import http_client
from six.moves.urllib import parse as urlparse
@@ -28,7 +29,8 @@ from oauth2client import client
from oauth2client import transport
METADATA_ROOT = 'http://metadata.google.internal/computeMetadata/v1/'
METADATA_ROOT = 'http://{}/computeMetadata/v1/'.format(
os.getenv('GCE_METADATA_ROOT', 'metadata.google.internal'))
METADATA_HEADERS = {'Metadata-Flavor': 'Google'}

View File

@@ -16,10 +16,12 @@
import datetime
import json
import os
import unittest
import mock
from six.moves import http_client
from six.moves import reload_module
from oauth2client import client
from oauth2client.contrib import _metadata
@@ -155,3 +157,19 @@ class AppAssertionCredentialsTests(unittest.TestCase):
client.save_to_well_known_file(credentials)
finally:
os.path.isdir = ORIGINAL_ISDIR
def test_custom_metadata_root_from_env(self):
headers = {'content-type': 'application/json'}
http = http_mock.HttpMock(headers=headers, data='{}')
fake_metadata_root = 'another.metadata.service'
os.environ['GCE_METADATA_ROOT'] = fake_metadata_root
reload_module(_metadata)
try:
_metadata.get(http, '')
finally:
del os.environ['GCE_METADATA_ROOT']
reload_module(_metadata)
# Verify mock.
self.assertEqual(http.requests, 1)
expected_uri = 'http://{}/computeMetadata/v1/'.format(fake_metadata_root)
self.assertEqual(http.uri, expected_uri)