Skip to content

Commit 1a7cfef

Browse files
authored
feat(env): Honor GCE_METADATA_HOST environment variable
1 parent 175c6f8 commit 1a7cfef

2 files changed

Lines changed: 30 additions & 2 deletions

File tree

google-cloud-env/lib/google/cloud/env.rb

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -82,6 +82,9 @@ class Env
8282
# well as mocking for testing.
8383
#
8484
# @param [Hash] env Mock environment variables.
85+
# @param [String] host The hostname or IP address of the metadata server.
86+
# Optional. If not specified, uses the `GCE_METADATA_HOST`,
87+
# environment variable or falls back to `169.254.167.254`.
8588
# @param [Hash,false] metadata_cache The metadata cache. You may pass
8689
# a prepopuated cache, an empty cache (the default) or `false` to
8790
# disable the cache completely.
@@ -102,7 +105,7 @@ class Env
102105
# If specified, overrides the `request_timeout` and `open_timeout`
103106
# settings.
104107
#
105-
def initialize env: nil, connection: nil, metadata_cache: nil,
108+
def initialize env: nil, host: nil, connection: nil, metadata_cache: nil,
106109
open_timeout: 0.1, request_timeout: 1.0,
107110
retry_count: 2, retry_interval: 0.1,
108111
retry_backoff_factor: 1.5, retry_max_interval: 0.5
@@ -114,7 +117,9 @@ def initialize env: nil, connection: nil, metadata_cache: nil,
114117
@retry_backoff_factor = retry_backoff_factor
115118
@retry_max_interval = retry_max_interval
116119
request_opts = { timeout: request_timeout, open_timeout: open_timeout }
117-
@connection = connection || ::Faraday.new(url: METADATA_HOST, request: request_opts)
120+
host ||= @env["GCE_METADATA_HOST"] || METADATA_HOST
121+
host = "http://#{host}" unless host.start_with? "http://"
122+
@connection = connection || ::Faraday.new(url: host, request: request_opts)
118123
end
119124

120125
##

google-cloud-env/test/google/cloud/env_test.rb

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -331,4 +331,27 @@ def ext_conn failure_count: 0
331331
connection: conn
332332
env.compute_engine?.must_equal true
333333
end
334+
335+
it "recognizes GCE_METADATA_HOST" do
336+
env_vars = { "GCE_METADATA_HOST" => "mymetadata.example.com" }
337+
callable = proc do |url:, **opts|
338+
assert_equal "http://mymetadata.example.com", url
339+
:callable
340+
end
341+
Faraday.stub :new, callable do
342+
env = ::Google::Cloud::Env.new env: env_vars
343+
assert_equal :callable, env.instance_variable_get(:@connection)
344+
end
345+
end
346+
347+
it "recognizes host override param" do
348+
callable = proc do |url:, **opts|
349+
assert_equal "http://mymetadata.example.com", url
350+
:callable
351+
end
352+
Faraday.stub :new, callable do
353+
env = ::Google::Cloud::Env.new host: "mymetadata.example.com"
354+
assert_equal :callable, env.instance_variable_get(:@connection)
355+
end
356+
end
334357
end

0 commit comments

Comments
 (0)