module Ohai::Mixin::GCEMetadata

Public Instance Methods

fetch_metadata(id = "") click to toggle source
# File lib/ohai/mixin/gce_metadata.rb, line 41
def fetch_metadata(id = "")
  url = "#{GCE_METADATA_URL}/#{id}"
  url = "#{url}?recursive=true" if url.end_with?("/")
  response = http_get(url)
  if response.code == "200"
    json_data = parse_json(response.body)
    if json_data.nil?
      logger.warn("Mixin GCEMetadata: Metadata response is NOT valid JSON for id='#{id}'")
      if has_trailing_slash?(id) || (id == "")
        temp = {}
        response.body.split("\n").each do |sub_attr|
          temp[sanitize_key(sub_attr)] = fetch_metadata("#{id}#{sub_attr}")
        end
        temp
      else
        response.body
      end
    else
      json_data
    end
  else
    logger.warn("Mixin GCEMetadata: Received response code #{response.code} requesting metadata for id='#{id}'")
    nil
  end
end
has_trailing_slash?(data) click to toggle source

@param data [String]

@return [Boolean] is there a trailing /?

# File lib/ohai/mixin/gce_metadata.rb, line 70
def has_trailing_slash?(data)
  !!( data =~ %r{/$} )
end
http_get(uri) click to toggle source

fetch the meta content with a timeout and the required header

# File lib/ohai/mixin/gce_metadata.rb, line 32
def http_get(uri)
  conn = Net::HTTP.start(GCE_METADATA_ADDR)
  conn.read_timeout = 6
  conn.get(uri, {
                  "Metadata-Flavor" => "Google",
                  "User-Agent" => "chef-ohai/#{Ohai::VERSION}",
                })
end
sanitize_key(key) click to toggle source
# File lib/ohai/mixin/gce_metadata.rb, line 74
def sanitize_key(key)
  key.gsub(%r{\-|/}, "_")
end