Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

puppet function: fact #13

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
65 changes: 65 additions & 0 deletions lib/puppet/functions/fact.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
# frozen_string_literal: true

# @summary
# Digs into the facts hash using dot-notation
#
# Supports the use of dot-notation for referring to structured facts. If a fact requested
# does not exist, returns Undef.
#
# @example Example usage:
# fact('osfamily')
# fact('os.architecture')
#
# @example Array indexing:
# fact('mountpoints."/dev".options.1')
#
# @example Fact containing a "." in the name:
# fact('vmware."VRA.version"')
#
Puppet::Functions.create_function(:fact) do
# @param fact_name
# The name of the fact to check
#
# @return
# All information retrieved on the given fact_name
dispatch :fact do
param 'String', :fact_name
end

def to_dot_syntax(array_path)
array_path.map { |string|
string.include?('.') ? %("#{string}") : string
}.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(%r{([^."]+)|(?:")([^"]+)(?:")}).map { |x| x.compact.first }

walked_path = []
path.reduce(facts) do |d, k|
return nil if d.nil? || k.nil?

if d.is_a?(Array)
begin
result = d[Integer(k)]
rescue ArgumentError => e # rubocop:disable Lint/UselessAssignment : Causes errors if assigment is removed.
Puppet.warning("fact request for #{fact_name} returning nil: '#{to_dot_syntax(walked_path)}' is an array; cannot index to '#{k}'")
result = nil
end
elsif 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