Class: Puppet::Application::Script

Inherits:
Puppet::Application show all
Defined in:
lib/puppet/application/script.rb

Constant Summary

Constants inherited from Puppet::Application

DOCPATTERN

Constants included from Util

Util::ALNUM, Util::ALPHA, Util::AbsolutePathPosix, Util::AbsolutePathWindows, Util::DEFAULT_POSIX_MODE, Util::DEFAULT_WINDOWS_MODE, Util::ESCAPED, Util::HEX, Util::HttpProxy, Util::PUPPET_STACK_INSERTION_FRAME, Util::RESERVED, Util::RFC_3986_URI_REGEX, Util::UNRESERVED, Util::UNSAFE

Constants included from Util::POSIX

Util::POSIX::LOCALE_ENV_VARS, Util::POSIX::USER_ENV_VARS

Constants included from Util::SymbolicFileMode

Util::SymbolicFileMode::SetGIDBit, Util::SymbolicFileMode::SetUIDBit, Util::SymbolicFileMode::StickyBit, Util::SymbolicFileMode::SymbolicMode, Util::SymbolicFileMode::SymbolicSpecialToBit

Instance Attribute Summary

Attributes inherited from Puppet::Application

#command_line, #options

Instance Method Summary collapse

Methods inherited from Puppet::Application

[], available_application_names, banner, clear!, clear?, clear_everything_for_tests, #configure_indirector_routes, controlled_run, #deprecate, #deprecated?, environment_mode, exit, find, get_environment_mode, #handle_logdest_arg, #handlearg, #initialize, #initialize_app_defaults, interrupted?, #log_runtime_environment, #name, option, option_parser_commands, #parse_options, #preinit, restart!, restart_requested?, #run, run_mode, #set_log_level, #setup_logs, stop!, stop_requested?, try_load_class

Methods included from Util

absolute_path?, benchmark, chuser, clear_environment, create_erb, default_env, deterministic_rand, deterministic_rand_int, exit_on_fail, format_backtrace_array, format_puppetstack_frame, get_env, get_environment, logmethods, merge_environment, path_to_uri, pretty_backtrace, replace_file, resolve_stackframe, rfc2396_escape, safe_posix_fork, set_env, skip_external_facts, symbolizehash, thinmark, uri_encode, uri_query_encode, uri_to_path, uri_unescape, which, withenv, withumask

Methods included from Util::POSIX

#get_posix_field, #gid, groups_of, #idfield, #methodbyid, #methodbyname, #search_posix_field, #uid

Methods included from Util::SymbolicFileMode

#display_mode, #normalize_symbolic_mode, #symbolic_mode_to_int, #valid_symbolic_mode?

Constructor Details

This class inherits a constructor from Puppet::Application

Instance Method Details

#app_defaultsObject



115
116
117
118
119
# File 'lib/puppet/application/script.rb', line 115

def app_defaults
  super.merge({
                :default_file_terminus => :file_server,
              })
end

#helpObject



24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
# File 'lib/puppet/application/script.rb', line 24

def help
  <<~HELP

    puppet-script(8) -- #{summary}
    ========

    SYNOPSIS
    --------
    Runs a puppet language script without compiling a catalog.


    USAGE
    -----
    puppet script [-h|--help] [-V|--version] [-d|--debug] [-v|--verbose]
      [-e|--execute]
      [-l|--logdest syslog|eventlog|<FILE>|console] [--noop]
      <file>


    DESCRIPTION
    -----------
    This is a standalone puppet script runner tool; use it to run puppet code
    without compiling a catalog.

    When provided with a modulepath, via command line or config file, puppet
    script can load functions, types, tasks and plans from modules.

    OPTIONS
    -------
    Note that any setting that's valid in the configuration
    file is also a valid long argument. For example, 'environment' is a
    valid setting, so you can specify '--environment mytest'
    as an argument.

    See the configuration file documentation at
    https://puppet.com/docs/puppet/latest/configuration.html for the
    full list of acceptable parameters. A commented list of all
    configuration options can also be generated by running puppet with
    '--genconfig'.

    * --debug:
      Enable full debugging.

    * --help:
      Print this help message


    * --logdest:
      Where to send log messages. Choose between 'syslog' (the POSIX syslog
      service), 'eventlog' (the Windows Event Log), 'console', or the path to a log
      file. Defaults to 'console'.
      Multiple destinations can be set using a comma separated list
      (eg: `/path/file1,console,/path/file2`)"

      A path ending with '.json' will receive structured output in JSON format. The
      log file will not have an ending ']' automatically written to it due to the
      appending nature of logging. It must be appended manually to make the content
      valid JSON.

      A path ending with '.jsonl' will receive structured output in JSON Lines
      format.

    * --noop:
      Use 'noop' mode where Puppet runs in a no-op or dry-run mode. This
      is useful for seeing what changes Puppet will make without actually
      executing the changes. Applies to tasks only.

    * --execute:
      Execute a specific piece of Puppet code

    * --verbose:
      Print extra information.

    EXAMPLE
    -------
        $ puppet script -l /tmp/manifest.log manifest.pp
        $ puppet script --modulepath=/root/dev/modules -e 'notice("hello world")'


    AUTHOR
    ------
    Henrik Lindberg


    COPYRIGHT
    ---------
    Copyright (c) 2017 Puppet Inc., LLC Licensed under the Apache 2.0 License

  HELP
end

#mainObject



131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
# File 'lib/puppet/application/script.rb', line 131

def main
  # The tasks feature is always on
  Puppet[:tasks] = true

  # Set the puppet code or file to use.
  if options[:code] || command_line.args.length == 0
    Puppet[:code] = options[:code] || STDIN.read
  else
    manifest = command_line.args.shift
    raise _("Could not find file %{manifest}") % { manifest: manifest } unless Puppet::FileSystem.exist?(manifest)

    Puppet.warning(_("Only one file can be used per run. Skipping %{files}") % { files: command_line.args.join(', ') }) if command_line.args.size > 0
  end

  unless Puppet[:node_name_fact].empty?
    # Collect the facts specified for that node
    facts = Puppet::Node::Facts.indirection.find(Puppet[:node_name_value])
    raise _("Could not find facts for %{node}") % { node: Puppet[:node_name_value] } unless facts

    Puppet[:node_name_value] = facts.values[Puppet[:node_name_fact]]
    facts.name = Puppet[:node_name_value]
  end

  # Find the Node
  node = Puppet::Node.indirection.find(Puppet[:node_name_value])
  raise _("Could not find node %{node}") % { node: Puppet[:node_name_value] } unless node

  configured_environment = node.environment || Puppet.lookup(:current_environment)

  apply_environment = manifest ?
    configured_environment.override_with(:manifest => manifest) :
    configured_environment

  # Modify the node descriptor to use the special apply_environment.
  # It is based on the actual environment from the node, or the locally
  # configured environment if the node does not specify one.
  # If a manifest file is passed on the command line, it overrides
  # the :manifest setting of the apply_environment.
  node.environment = apply_environment

  # TRANSLATION, the string "For puppet script" is not user facing
  Puppet.override({ :current_environment => apply_environment }, "For puppet script") do
    # Merge in the facts.
    node.merge(facts.values) if facts

    # Add server facts so $server_facts[environment] exists when doing a puppet script
    # SCRIPT TODO: May be needed when running scripts under orchestrator. Leave it for now.
    #
    node.add_server_facts({})

    begin
      # Compile the catalog

      # When compiling, the compiler traps and logs certain errors
      # Those that do not lead to an immediate exit are caught by the general
      # rule and gets logged.
      #
      begin
        # support the following features when evaluating puppet code
        # * $facts with facts from host running the script
        # * $settings with 'settings::*' namespace populated, and '$settings::all_local' hash
        # * $trusted as setup when using puppet apply
        # * an environment
        #

        # fixup trusted information
        node.sanitize()

        compiler = Puppet::Parser::ScriptCompiler.new(node.environment, node.name)
        topscope = compiler.topscope

        # When scripting the trusted data are always local, but set them anyway
        topscope.set_trusted(node.trusted_data)

        # Server facts are always about the local node's version etc.
        topscope.set_server_facts(node.server_facts)

        # Set $facts for the node running the script
        facts_hash = node.facts.nil? ? {} : node.facts.values
        topscope.set_facts(facts_hash)

        # create the $settings:: variables
        topscope.merge_settings(node.environment.name, false)

        compiler.compile()
      rescue Puppet::Error
        # already logged and handled by the compiler, including Puppet::ParseErrorWithIssue
        exit(1)
      end

      exit(0)
    rescue => detail
      Puppet.log_exception(detail)
      exit(1)
    end
  end
ensure
  if @profiler
    Puppet::Util::Profiler.remove_profiler(@profiler)
    @profiler.shutdown
  end
end

#run_commandObject



121
122
123
124
125
126
127
128
129
# File 'lib/puppet/application/script.rb', line 121

def run_command
  if Puppet.features.bolt?
    Puppet.override(:bolt_executor => Bolt::Executor.new) do
      main
    end
  else
    raise _("Bolt must be installed to use the script application")
  end
end

#setupObject



234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
# File 'lib/puppet/application/script.rb', line 234

def setup
  exit(Puppet.settings.print_configs ? 0 : 1) if Puppet.settings.print_configs?

  handle_logdest_arg(Puppet[:logdest])
  Puppet::Util::Log.newdestination(:console) unless options[:setdest]

  Signal.trap(:INT) do
    $stderr.puts _("Exiting")
    exit(1)
  end

  # TODO: This skips applying the settings catalog for these settings, but
  # the effect of doing this is unknown. It may be that it only works if there is a puppet
  # installed where a settings catalog have already been applied...
  # This saves 1/5th of the startup time

  #    Puppet.settings.use :main, :agent, :ssl

  # When running a script, the catalog is not relevant, and neither is caching of it
  Puppet::Resource::Catalog.indirection.cache_class = nil

  # we do not want the last report to be persisted
  Puppet::Transaction::Report.indirection.cache_class = nil

  set_log_level

  if Puppet[:profile]
    @profiler = Puppet::Util::Profiler.add_profiler(Puppet::Util::Profiler::Aggregate.new(Puppet.method(:info), "script"))
  end
end

#summaryObject



20
21
22
# File 'lib/puppet/application/script.rb', line 20

def summary
  _("Run a puppet manifests as a script without compiling a catalog")
end