class Puppet::Application::Lookup

Constants

DEEP_MERGE_OPTIONS
RUN_HELP
TRUSTED_INFORMATION_FACTS

Public Instance Methods

app_defaults() click to toggle source
Calls superclass method Puppet::Application#app_defaults
   # File lib/puppet/application/lookup.rb
62 def app_defaults
63   super.merge({
64     :facts_terminus => 'yaml'
65   })
66 end
generate_scope() { |topscope| ... } click to toggle source
    # File lib/puppet/application/lookup.rb
341 def generate_scope
342   if options[:node]
343     node = options[:node]
344   else
345     node = Puppet[:node_name_value]
346 
347     # If we want to lookup the node we are currently on
348     # we must returning these settings to their default values
349     Puppet.settings[:facts_terminus] = 'facter'
350   end
351 
352   fact_file = options[:fact_file]
353 
354   if fact_file
355     if fact_file.end_with?('.json')
356       given_facts = Puppet::Util::Json.load_file(fact_file)
357     elsif fact_file.end_with?('.yml', '.yaml')
358       given_facts = Puppet::Util::Yaml.safe_load_file(fact_file)
359     else
360       given_facts = Puppet::Util::Json.load_file_if_valid(fact_file)
361       given_facts = Puppet::Util::Yaml.safe_load_file_if_valid(fact_file) unless given_facts
362     end
363 
364     unless given_facts.instance_of?(Hash)
365       raise _("Incorrectly formatted data in %{fact_file} given via the --facts flag (only accepts yaml and json files)") % { fact_file: fact_file }
366     end
367 
368     if TRUSTED_INFORMATION_FACTS.any? { |key| given_facts.key? key }
369       unless TRUSTED_INFORMATION_FACTS.all? { |key| given_facts.key? key }
370         raise _("When overriding any of the %{trusted_facts_list} facts with %{fact_file} "\
371           "given via the --facts flag, they must all be overridden.") % { fact_file: fact_file ,trusted_facts_list: TRUSTED_INFORMATION_FACTS.join(',')}
372       end
373     end
374   end
375 
376   unless node.is_a?(Puppet::Node) # to allow unit tests to pass a node instance
377     facts = retrieve_node_facts(node, given_facts)
378     ni = Puppet::Node.indirection
379     tc = ni.terminus_class
380     if options[:compile]
381       if tc == :plain
382         node = ni.find(node, facts: facts, environment: Puppet[:environment])
383       else
384         begin
385           service = Puppet.runtime[:http]
386           session = service.create_session
387           cert = session.route_to(:ca)
388 
389           _, x509 = cert.get_certificate(node)
390           cert = OpenSSL::X509::Certificate.new(x509)
391           Puppet::SSL::Oids.register_puppet_oids
392           trusted = Puppet::Context::TrustedInformation.remote(true, facts.values['certname'] || node, Puppet::SSL::Certificate.from_instance(cert))
393           Puppet.override(trusted_information: trusted) do
394             node = ni.find(node, facts: facts, environment: Puppet[:environment])
395           end
396         rescue
397           Puppet.warning _("CA is not available, the operation will continue without using trusted facts.")
398           node = ni.find(node, facts: facts, environment: Puppet[:environment])
399         end
400       end
401     else
402       ni.terminus_class = :plain
403       node = ni.find(node, facts: facts, environment: Puppet[:environment])
404       ni.terminus_class = tc
405     end
406   else
407     node.add_extra_facts(given_facts) if given_facts
408   end
409   node.environment = Puppet[:environment] if Puppet.settings.set_by_cli?(:environment)
410   Puppet[:code] = 'undef' unless options[:compile]
411   compiler = Puppet::Parser::Compiler.new(node)
412   if options[:node]
413     Puppet::Util.skip_external_facts do
414       compiler.compile { |catalog| yield(compiler.topscope); catalog }
415     end
416   else
417     compiler.compile { |catalog| yield(compiler.topscope); catalog }
418   end
419 end
help() click to toggle source
    # File lib/puppet/application/lookup.rb
106   def help
107     <<-HELP
108 
109 puppet-lookup(8) -- #{summary}
110 ========
111 
112 SYNOPSIS
113 --------
114 Does Hiera lookups from the command line.
115 
116 Since this command needs access to your Hiera data, make sure to run it on a
117 node that has a copy of that data. This usually means logging into a Puppet
118 Server node and running 'puppet lookup' with sudo.
119 
120 The most common version of this command is:
121 
122 'puppet lookup <KEY> --node <NAME> --environment <ENV> --explain'
123 
124 USAGE
125 -----
126 puppet lookup [--help] [--type <TYPESTRING>] [--merge first|unique|hash|deep]
127   [--knock-out-prefix <PREFIX-STRING>] [--sort-merged-arrays]
128   [--merge-hash-arrays] [--explain] [--environment <ENV>]
129   [--default <VALUE>] [--node <NODE-NAME>] [--facts <FILE>]
130   [--compile]
131   [--render-as s|json|yaml|binary|msgpack] <keys>
132 
133 DESCRIPTION
134 -----------
135 The lookup command is a CLI for Puppet's 'lookup()' function. It searches your
136 Hiera data and returns a value for the requested lookup key, so you can test and
137 explore your data. It is a modern replacement for the 'hiera' command.
138 Lookup uses the setting for global hiera.yaml from puppet's config,
139 and the environment to find the environment level hiera.yaml as well as the
140 resulting modulepath for the environment (for hiera.yaml files in modules).
141 Hiera usually relies on a node's facts to locate the relevant data sources. By
142 default, 'puppet lookup' uses facts from the node you run the command on, but
143 you can get data for any other node with the '--node <NAME>' option. If
144 possible, the lookup command will use the requested node's real stored facts
145 from PuppetDB; if PuppetDB isn't configured or you want to provide arbitrary
146 fact values, you can pass alternate facts as a JSON or YAML file with '--facts
147 <FILE>'.
148 
149 If you're debugging your Hiera data and want to see where values are coming
150 from, use the '--explain' option.
151 
152 If '--explain' isn't specified, lookup exits with 0 if a value was found and 1
153 otherwise. With '--explain', lookup always exits with 0 unless there is a major
154 error.
155 
156 You can provide multiple lookup keys to this command, but it only returns a
157 value for the first found key, omitting the rest.
158 
159 For more details about how Hiera works, see the Hiera documentation:
160 https://puppet.com/docs/puppet/latest/hiera_intro.html
161 
162 OPTIONS
163 -------
164 
165 * --help:
166   Print this help message.
167 
168 * --explain
169   Explain the details of how the lookup was performed and where the final value
170   came from (or the reason no value was found).
171 
172 * --node <NODE-NAME>
173   Specify which node to look up data for; defaults to the node where the command
174   is run. Since Hiera's purpose is to provide different values for different
175   nodes (usually based on their facts), you'll usually want to use some specific
176   node's facts to explore your data. If the node where you're running this
177   command is configured to talk to PuppetDB, the command will use the requested
178   node's most recent facts. Otherwise, you can override facts with the '--facts'
179   option.
180 
181 * --facts <FILE>
182   Specify a .json or .yaml file of key => value mappings to override the facts
183   for this lookup. Any facts not specified in this file maintain their
184   original value.
185 
186 * --environment <ENV>
187   Like with most Puppet commands, you can specify an environment on the command
188   line. This is important for lookup because different environments can have
189   different Hiera data. This environment will be always be the one used regardless
190   of any other factors.
191 
192 * --merge first|unique|hash|deep:
193   Specify the merge behavior, overriding any merge behavior from the data's
194   lookup_options. 'first' returns the first value found. 'unique' appends
195   everything to a merged, deduplicated array. 'hash' performs a simple hash
196   merge by overwriting keys of lower lookup priority. 'deep' performs a deep
197   merge on values of Array and Hash type. There are additional options that can
198   be used with 'deep'.
199 
200 * --knock-out-prefix <PREFIX-STRING>
201   Can be used with the 'deep' merge strategy. Specifies a prefix to indicate a
202   value should be removed from the final result.
203 
204 * --sort-merged-arrays
205   Can be used with the 'deep' merge strategy. When this flag is used, all
206   merged arrays are sorted.
207 
208 * --merge-hash-arrays
209   Can be used with the 'deep' merge strategy. When this flag is used, hashes
210   WITHIN arrays are deep-merged with their counterparts by position.
211 
212 * --explain-options
213   Explain whether a lookup_options hash affects this lookup, and how that hash
214   was assembled. (lookup_options is how Hiera configures merge behavior in data.)
215 
216 * --default <VALUE>
217   A value to return if Hiera can't find a value in data. For emulating calls to
218   the 'lookup()' function that include a default.
219 
220 * --type <TYPESTRING>:
221   Assert that the value has the specified type. For emulating calls to the
222   'lookup()' function that include a data type.
223 
224 * --compile
225   Perform a full catalog compilation prior to the lookup. If your hierarchy and
226   data only use the $facts, $trusted, and $server_facts variables, you don't
227   need this option; however, if your Hiera configuration uses arbitrary
228   variables set by a Puppet manifest, you might need this option to get accurate
229   data. No catalog compilation takes place unless this flag is given.
230 
231 * --render-as s|json|yaml|binary|msgpack
232   Specify the output format of the results; "s" means plain text. The default
233   when producing a value is yaml and the default when producing an explanation
234   is s.
235 
236 EXAMPLE
237 -------
238   To look up 'key_name' using the Puppet Server node's facts:
239   $ puppet lookup key_name
240 
241   To look up 'key_name' using the Puppet Server node's arbitrary variables from a manifest, and 
242   classify the node if applicable:
243   $ puppet lookup key_name --compile
244 
245   To look up 'key_name' using the Puppet Server node's facts, overridden by facts given in a file:
246   $ puppet lookup key_name --facts fact_file.yaml
247 
248   To look up 'key_name' with agent.local's facts:
249   $ puppet lookup --node agent.local key_name
250 
251   To get the first value found for 'key_name_one' and 'key_name_two'
252   with agent.local's facts while merging values and knocking out
253   the prefix 'foo' while merging:
254   $ puppet lookup --node agent.local --merge deep --knock-out-prefix foo key_name_one key_name_two
255 
256   To lookup 'key_name' with agent.local's facts, and return a default value of
257   'bar' if nothing was found:
258   $ puppet lookup --node agent.local --default bar key_name
259 
260   To see an explanation of how the value for 'key_name' would be found, using
261   agent.local's facts:
262   $ puppet lookup --node agent.local --explain key_name
263 
264 COPYRIGHT
265 ---------
266 Copyright (c) 2015 Puppet Inc., LLC Licensed under the Apache 2.0 License
267 
268 
269     HELP
270   end
main() click to toggle source
    # File lib/puppet/application/lookup.rb
272 def main
273   keys = command_line.args
274 
275   #unless options[:node]
276   #  raise "No node was given via the '--node' flag for the scope of the lookup.\n#{RUN_HELP}"
277   #end
278 
279   if (options[:sort_merged_arrays] || options[:merge_hash_arrays] || options[:prefix]) && options[:merge] != 'deep'
280     raise _("The options %{deep_merge_opts} are only available with '--merge deep'\n%{run_help}") % { deep_merge_opts: DEEP_MERGE_OPTIONS, run_help: RUN_HELP }
281   end
282 
283   use_default_value = !options[:default_value].nil?
284   merge_options = nil
285 
286   merge = options[:merge]
287   unless merge.nil?
288     strategies = Puppet::Pops::MergeStrategy.strategy_keys
289     unless strategies.include?(merge.to_sym)
290       strategies = strategies.map {|k| "'#{k}'"}
291       raise _("The --merge option only accepts %{strategies}, or %{last_strategy}\n%{run_help}") % { strategies: strategies[0...-1].join(', '), last_strategy: strategies.last, run_help: RUN_HELP }
292     end
293 
294     if merge == 'deep'
295       merge_options = {'strategy' => 'deep',
296         'sort_merged_arrays' => !options[:sort_merged_arrays].nil?,
297         'merge_hash_arrays' => !options[:merge_hash_arrays].nil?}
298 
299       if options[:prefix]
300         merge_options['knockout_prefix'] = options[:prefix]
301       end
302 
303     else
304       merge_options = {'strategy' => merge}
305     end
306   end
307 
308   explain_data = !!options[:explain]
309   explain_options = !!options[:explain_options]
310   only_explain_options = explain_options && !explain_data
311   if keys.empty?
312     if only_explain_options
313       # Explain lookup_options for lookup of an unqualified value.
314       keys = Puppet::Pops::Lookup::GLOBAL
315     else
316       raise _('No keys were given to lookup.')
317     end
318   end
319   explain = explain_data || explain_options
320 
321   # Format defaults to text (:s) when producing an explanation and :yaml when producing the value
322   format = options[:render_as] || (explain ? :s : :yaml)
323   renderer = Puppet::Network::FormatHandler.format(format)
324   raise _("Unknown rendering format '%{format}'") % { format: format } if renderer.nil?
325 
326   generate_scope do |scope|
327     lookup_invocation = Puppet::Pops::Lookup::Invocation.new(scope, {}, {}, explain ? Puppet::Pops::Lookup::Explainer.new(explain_options, only_explain_options) : nil)
328     begin
329       type = options.include?(:type) ? Puppet::Pops::Types::TypeParser.singleton.parse(options[:type], scope) : nil
330       result = Puppet::Pops::Lookup.lookup(keys, type, options[:default_value], use_default_value, merge_options, lookup_invocation)
331       puts renderer.render(result) unless explain
332     rescue Puppet::DataBinding::LookupError => e
333       lookup_invocation.report_text { e.message }
334       exit(1) unless explain
335     end
336     puts format == :s ? lookup_invocation.explainer.explain : renderer.render(lookup_invocation.explainer.to_hash) if explain
337   end
338   exit(0)
339 end
retrieve_node_facts(node, given_facts) click to toggle source
    # File lib/puppet/application/lookup.rb
421 def retrieve_node_facts(node, given_facts)
422   facts = Puppet::Node::Facts.indirection.find(node, :environment => Puppet.lookup(:current_environment))
423 
424   facts = Puppet::Node::Facts.new(node, {}) if facts.nil?
425   facts.add_extra_values(given_facts) if given_facts
426 
427   if facts.values.empty?
428     raise _("No facts available for target node: %{node}") % { node: node}
429   end
430   facts
431 end
setup() click to toggle source
    # File lib/puppet/application/lookup.rb
 86 def setup
 87   setup_logs
 88 
 89   exit(Puppet.settings.print_configs ? 0 : 1) if Puppet.settings.print_configs?
 90 
 91   if options[:node]
 92     Puppet::Util.skip_external_facts do
 93       Puppet.settings.use :main, :server, :ssl, :metrics
 94     end
 95   else
 96     Puppet.settings.use :main, :server, :ssl, :metrics
 97   end
 98 
 99   setup_terminuses
100 end
setup_logs() click to toggle source
   # File lib/puppet/application/lookup.rb
68 def setup_logs
69   # This sets up logging based on --debug or --verbose if they are set in `options`
70   set_log_level
71 
72   # This uses console for everything that is not a compilation
73   Puppet::Util::Log.newdestination(:console)
74 end
setup_terminuses() click to toggle source
   # File lib/puppet/application/lookup.rb
76 def setup_terminuses
77   require_relative '../../puppet/file_serving/content'
78   require_relative '../../puppet/file_serving/metadata'
79 
80   Puppet::FileServing::Content.indirection.terminus_class = :file_server
81   Puppet::FileServing::Metadata.indirection.terminus_class = :file_server
82 
83   Puppet::FileBucket::File.indirection.terminus_class = :file
84 end
summary() click to toggle source
    # File lib/puppet/application/lookup.rb
102 def summary
103   _("Interactive Hiera lookup")
104 end