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::AbsolutePathPosix, Util::AbsolutePathWindows, Util::DEFAULT_POSIX_MODE, Util::DEFAULT_WINDOWS_MODE, Util::RFC_3986_URI_REGEX

Constants included from Util::SymbolicFileMode

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

Constants included from Util::POSIX

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

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, default_env, deterministic_rand, deterministic_rand_int, exit_on_fail, get_env, get_environment, logmethods, merge_environment, path_to_uri, pretty_backtrace, replace_file, safe_posix_fork, set_env, symbolizehash, thinmark, uri_encode, uri_query_encode, uri_to_path, which, withenv, withumask

Methods included from Util::SymbolicFileMode

#normalize_symbolic_mode, #symbolic_mode_to_int, #valid_symbolic_mode?

Methods included from Util::POSIX

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

Constructor Details

This class inherits a constructor from Puppet::Application

Instance Method Details

#app_defaultsObject


112
113
114
115
116
# File 'lib/puppet/application/script.rb', line 112

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

#helpObject


23
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
# File 'lib/puppet/application/script.rb', line 23

def help
  "\npuppet-script(8) -- \#{summary}\n========\n\nSYNOPSIS\n--------\nRuns a puppet language script without compiling a catalog.\n\n\nUSAGE\n-----\npuppet script [-h|--help] [-V|--version] [-d|--debug] [-v|--verbose]\n[-e|--execute]\n[-l|--logdest syslog|eventlog|<FILE>|console] [--noop]\n<file>\n\n\nDESCRIPTION\n-----------\nThis is a standalone puppet script runner tool; use it to run puppet code\nwithout compiling a catalog.\n\nWhen provided with a modulepath, via command line or config file, puppet\nscript can load functions, types, tasks and plans from modules.\n\nOPTIONS\n-------\nNote that any setting that's valid in the configuration\nfile is also a valid long argument. For example, 'environment' is a\nvalid setting, so you can specify '--environment mytest'\nas an argument.\n\nSee the configuration file documentation at\nhttps://puppet.com/docs/puppet/latest/configuration.html for the\nfull list of acceptable parameters. A commented list of all\nconfiguration options can also be generated by running puppet with\n'--genconfig'.\n\n* --debug:\nEnable full debugging.\n\n* --help:\nPrint this help message\n\n\n* --logdest:\nWhere to send log messages. Choose between 'syslog' (the POSIX syslog\nservice), 'eventlog' (the Windows Event Log), 'console', or the path to a log\nfile. Defaults to 'console'.\n\nA path ending with '.json' will receive structured output in JSON format. The\nlog file will not have an ending ']' automatically written to it due to the\nappending nature of logging. It must be appended manually to make the content\nvalid JSON.\n\nA path ending with '.jsonl' will receive structured output in JSON Lines\nformat.\n\n* --noop:\nUse 'noop' mode where Puppet runs in a no-op or dry-run mode. This\nis useful for seeing what changes Puppet will make without actually\nexecuting the changes. Applies to tasks only.\n\n* --execute:\nExecute a specific piece of Puppet code\n\n* --verbose:\nPrint extra information.\n\nEXAMPLE\n-------\n$ puppet script -l /tmp/manifest.log manifest.pp\n$ puppet script --modulepath=/root/dev/modules -e 'notice(\"hello world\")'\n\n\nAUTHOR\n------\nHenrik Lindberg\n\n\nCOPYRIGHT\n---------\nCopyright (c) 2017 Puppet Inc., LLC Licensed under the Apache 2.0 License\n\n"
end

#mainObject


128
129
130
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
# File 'lib/puppet/application/script.rb', line 128

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


118
119
120
121
122
123
124
125
126
# File 'lib/puppet/application/script.rb', line 118

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


232
233
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
# File 'lib/puppet/application/script.rb', line 232

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


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

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