module Ohai::Mixin::GCEMetadata
Public Instance Methods
fetch_metadata(id = "")
click to toggle source
# File lib/ohai/mixin/gce_metadata.rb, line 38 def fetch_metadata(id = "") response = http_get("#{GCE_METADATA_URL}/#{id}") return nil unless response.code == "200" if json?(response.body) data = StringIO.new(response.body) parser = FFI_Yajl::Parser.new parser.parse(data) elsif 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 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 74 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 28 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
json?(data)
click to toggle source
@param [String] data that might be JSON
@return [Boolean] is the data JSON or not?
# File lib/ohai/mixin/gce_metadata.rb, line 60 def json?(data) data = StringIO.new(data) parser = FFI_Yajl::Parser.new begin parser.parse(data) true rescue FFI_Yajl::ParseError false end end
sanitize_key(key)
click to toggle source
# File lib/ohai/mixin/gce_metadata.rb, line 78 def sanitize_key(key) key.gsub(/\-|\//, "_") end