summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorHunter Haugen <hunter@puppet.com>2017-07-21 11:29:45 -0700
committerHunter Haugen <hunter@puppet.com>2017-07-21 11:29:45 -0700
commit539ba5d8a78f0f41736d605e0027ef61113ed515 (patch)
tree2219fd060f4d3973f5f559698ef3eaf40dc43227
parent1b30d0d98ec93a01b3ff78246147e63d670dcbbb (diff)
parent0f35700487368357adec8a535b5c50437b208264 (diff)
Merge pull request #787 from reidmv/fact_function
(FACT-932) Add new function, fact()
-rw-r--r--lib/puppet/functions/fact.rb58
1 files changed, 58 insertions, 0 deletions
diff --git a/lib/puppet/functions/fact.rb b/lib/puppet/functions/fact.rb
new file mode 100644
index 0000000..dfb048b
--- /dev/null
+++ b/lib/puppet/functions/fact.rb
@@ -0,0 +1,58 @@
+# Digs into the facts hash using dot-notation
+#
+# Example usage:
+#
+# fact('osfamily')
+# fact('os.architecture')
+#
+# Array indexing:
+#
+# fact('mountpoints."/dev".options.1')
+#
+# Fact containing a "." in the name:
+#
+# fact('vmware."VRA.version"')
+#
+Puppet::Functions.create_function(:fact) do
+ dispatch :fact do
+ param 'String', :fact_name
+ end
+
+ def to_dot_syntax(array_path)
+ array_path.map do |string|
+ string.include?('.') ? %Q{"#{string}"} : string
+ end.join('.')
+ end
+
+ def fact(fact_name)
+ facts = closure_scope['facts']
+
+ # Transform the dot-notation string into an array of paths to walk. Make
+ # sure to correctly extract double-quoted values containing dots as single
+ # elements in the path.
+ path = fact_name.scan(/([^."]+)|(?:")([^"]+)(?:")/).map {|x| x.compact.first }
+
+ walked_path = []
+ path.reduce(facts) do |d, k|
+ return nil if d.nil? || k.nil?
+
+ case
+ when d.is_a?(Array)
+ begin
+ result = d[Integer(k)]
+ rescue ArgumentError => e
+ Puppet.warning("fact request for #{fact_name} returning nil: '#{to_dot_syntax(walked_path)}' is an array; cannot index to '#{k}'")
+ result = nil
+ end
+ when d.is_a?(Hash)
+ result = d[k]
+ else
+ Puppet.warning("fact request for #{fact_name} returning nil: '#{to_dot_syntax(walked_path)}' is not a collection; cannot walk to '#{k}'")
+ result = nil
+ end
+
+ walked_path << k
+ result
+ end
+ end
+end