Skip to content

Instantly share code, notes, and snippets.

@robrwo
Last active November 14, 2017 10:52
Show Gist options
  • Save robrwo/9411981 to your computer and use it in GitHub Desktop.
Save robrwo/9411981 to your computer and use it in GitHub Desktop.
Query puppet configuration from a file
module Puppet::Parser::Functions
newfunction(:puppet_config, :type => :rvalue, :doc => <<-EOS
This function queries Puppet configuration files.
*Examples:*
puppet_config('/etc/puppetlabs/installer/answers.install', 'q_install')
Will return: 'y'
Note that the pe-puppet user must be able to read the file.
EOS
) do |arguments|
# Technically we support two arguments but only first is mandatory ...
raise(Puppet::ParseError, "puppet_config(): Wrong number of arguments " +
"given (#{arguments.size} for 2)") if arguments.size < 2
filename = arguments[0]
unless filename.is_a? String
raise Puppet::ParseError "puppet_config(): expected first argument to be a String, got #{filename.inspect}"
end
# unless Puppet::FileSystem.exist?(filename)
# raise Puppet::ParseError "puppet_config(): file #{filename} does not exist"
# end
key = arguments[1]
unless key.is_a? String
raise Puppet::ParseError "puppet_config(): expected second argument to be a String, got #{key.inspect}"
end
default = arguments[2]
if default
unless default.is_a? String
raise Puppet::ParseError "puppet_config(): expected third argument to be a String, got #{default.inspect}"
end
else
default = ''
end
parser = Puppet::Parser::Parser.new(environment)
parser.watch_file(filename)
config = IO.readlines(filename)
match = config.detect{ |line| line.match(/^\s*#{key}\s*=\s*/) }
if (match != :Null)
return match.sub(/^\s*#{key}\s*=\s*/, '').sub(/\n$/, '')
else
return default
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment