Class: Facter::EC2::Metadata

Inherits:
Base
  • Object
show all
Defined in:
lib/facter/ec2/rest.rb

Constant Summary collapse

DEFAULT_URI =
"http://169.254.169.254/latest/meta-data/"

Instance Method Summary collapse

Methods inherited from Base

#reachable?

Constructor Details

#initialize(uri = DEFAULT_URI) ⇒ Metadata

Returns a new instance of Metadata.



50
51
52
# File 'lib/facter/ec2/rest.rb', line 50

def initialize(uri = DEFAULT_URI)
  @baseurl = uri
end

Instance Method Details

#fetch(path = '') ⇒ Object



54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
# File 'lib/facter/ec2/rest.rb', line 54

def fetch(path = '')
  results = {}

  keys = fetch_endpoint(path)
  keys.each do |key|
    if key.match(%r[/$])
      # If a metadata key is suffixed with '/' then it's a general metadata
      # resource, so we have to recursively look up all the keys in the given
      # collection.
      name = key[0..-2]
      results[name] = fetch("#{path}#{key}")
    else
      # This is a simple key/value pair, we can just query the given endpoint
      # and store the results.
      ret = fetch_endpoint("#{path}#{key}")
      results[key] = ret.size > 1 ? ret : ret.first
    end
  end

  results
end

#fetch_endpoint(path) ⇒ Array, NilClass

Parameters:

  • path (String)

    The path relative to the object base url

Returns:



79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
# File 'lib/facter/ec2/rest.rb', line 79

def fetch_endpoint(path)
  uri = @baseurl + path
  body = open(uri, :proxy => nil).read
  parse_results(body)
rescue OpenURI::HTTPError => e
  if e.message.match /404 Not Found/i
    return nil
  else
    Facter.log_exception(e, "Failed to fetch ec2 uri #{uri}: #{e.message}")
    return nil
  end
rescue *CONNECTION_ERRORS => e
  Facter.log_exception(e, "Failed to fetch ec2 uri #{uri}: #{e.message}")
  return nil
end