Class: Bolt::CLI
- Inherits:
-
Object
- Object
- Bolt::CLI
- Defined in:
- lib/bolt/cli.rb
Constant Summary collapse
- COMMANDS =
{ 'command' => %w[run], 'script' => %w[run], 'task' => %w[show run], 'plan' => %w[show run], 'file' => %w[upload], 'puppetfile' => %w[install show-modules], 'apply' => %w[] }.freeze
Instance Attribute Summary collapse
-
#config ⇒ Object
readonly
Returns the value of attribute config.
-
#options ⇒ Object
readonly
Returns the value of attribute options.
Instance Method Summary collapse
- #apply_manifest(code, targets, filename = nil, noop = false) ⇒ Object
- #bundled_content ⇒ Object
- #execute(options) ⇒ Object
- #file_stat(path) ⇒ Object
- #handle_parser_errors ⇒ Object
-
#initialize(argv) ⇒ CLI
constructor
A new instance of CLI.
- #install_puppetfile(puppetfile, modulepath) ⇒ Object
- #list_modules ⇒ Object
- #list_plans ⇒ Object
- #list_tasks ⇒ Object
- #outputter ⇒ Object
- #pal ⇒ Object
- #parse ⇒ Object
- #puppetdb_client ⇒ Object
- #query_puppetdb_nodes(query) ⇒ Object
- #run_plan(plan_name, plan_arguments, nodes, options) ⇒ Object
- #show_plan(plan_name) ⇒ Object
- #show_task(task_name) ⇒ Object
- #validate(options) ⇒ Object
- #validate_file(type, path, allow_dir = false) ⇒ Object
Constructor Details
Instance Attribute Details
#config ⇒ Object (readonly)
Returns the value of attribute config.
36 37 38 |
# File 'lib/bolt/cli.rb', line 36 def config @config end |
#options ⇒ Object (readonly)
Returns the value of attribute options.
36 37 38 |
# File 'lib/bolt/cli.rb', line 36 def @options end |
Instance Method Details
#apply_manifest(code, targets, filename = nil, noop = false) ⇒ Object
386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 |
# File 'lib/bolt/cli.rb', line 386 def apply_manifest(code, targets, filename = nil, noop = false) ast = pal.parse_manifest(code, filename) executor = Bolt::Executor.new(config.concurrency, @analytics, noop, bundled_content: bundled_content) # Call start_plan just to enable plan_logging executor.start_plan(nil) pal.in_plan_compiler(executor, inventory, puppetdb_client) do |compiler| compiler.call_function('apply_prep', targets) end results = pal.with_bolt_executor(executor, inventory, puppetdb_client) do Puppet.lookup(:apply_executor).apply_ast(ast, targets, '_catch_errors' => true, '_noop' => noop) end outputter.print_apply_result(results) results.ok ? 0 : 1 end |
#bundled_content ⇒ Object
471 472 473 474 475 476 477 478 479 480 481 482 |
# File 'lib/bolt/cli.rb', line 471 def bundled_content if %w[plan task].include?([:subcommand]) default_content = Bolt::PAL.new([], nil) plans = default_content.list_plans.each_with_object([]) do |iter, col| col << iter&.first end tasks = default_content.list_tasks.each_with_object([]) do |iter, col| col << iter&.first end plans.concat tasks end end |
#execute(options) ⇒ Object
223 224 225 226 227 228 229 230 231 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 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 |
# File 'lib/bolt/cli.rb', line 223 def execute() = nil handler = Signal.trap :INT do |signo| @logger.info( "Exiting after receiving SIG#{Signal.signame(signo)} signal.#{ ? ' ' + : ''}" ) exit! end @analytics = Bolt::Analytics.build_client screen = "#{[:subcommand]}_#{[:action]}" # submit a different screen for `bolt task show` and `bolt task show foo` if [:action] == 'show' && [:object] screen += '_object' end @analytics.screen_view(screen, output_format: config.format, target_nodes: .fetch(:targets, []).count, inventory_nodes: inventory.node_names.count, inventory_groups: inventory.group_names.count) if [:action] == 'show' if [:subcommand] == 'task' if [:object] show_task([:object]) else list_tasks end elsif [:subcommand] == 'plan' if [:object] show_plan([:object]) else list_plans end end return 0 elsif [:action] == 'show-modules' list_modules return 0 end = 'There may be processes left executing on some nodes.' if %w[task plan].include?([:subcommand]) && [:task_options] && ![:params_parsed] && pal [:task_options] = pal.parse_params([:subcommand], [:object], [:task_options]) end case [:subcommand] when 'plan' code = run_plan([:object], [:task_options], [:nodes], ) when 'puppetfile' code = install_puppetfile(@config.puppetfile, @config.modulepath) when 'apply' if [:object] validate_file('manifest', [:object]) [:code] = File.read(File.([:object])) end code = apply_manifest([:code], [:targets], [:object], [:noop]) else executor = Bolt::Executor.new(config.concurrency, @analytics, [:noop], bundled_content: bundled_content) targets = [:targets] results = nil outputter.print_head elapsed_time = Benchmark.realtime do executor_opts = {} executor_opts['_description'] = [:description] if .key?(:description) results = case [:subcommand] when 'command' executor.run_command(targets, [:object], executor_opts) do |event| outputter.print_event(event) end when 'script' script = [:object] validate_file('script', script) executor.run_script( targets, script, [:leftovers], executor_opts ) do |event| outputter.print_event(event) end when 'task' pal.run_task([:object], targets, [:task_options], executor, inventory, [:description]) do |event| outputter.print_event(event) end when 'file' src = [:object] dest = [:leftovers].first if dest.nil? raise Bolt::CLIError, "A destination path must be specified" end validate_file('source file', src, true) executor.upload_file(targets, src, dest, executor_opts) do |event| outputter.print_event(event) end end end outputter.print_summary(results, elapsed_time) code = results.ok ? 0 : 2 end code rescue Bolt::Error => e outputter.fatal_error(e) raise e ensure # restore original signal handler Signal.trap :INT, handler if handler @analytics&.finish end |
#file_stat(path) ⇒ Object
463 464 465 |
# File 'lib/bolt/cli.rb', line 463 def file_stat(path) File.stat(path) end |
#handle_parser_errors ⇒ Object
203 204 205 206 207 208 209 210 211 |
# File 'lib/bolt/cli.rb', line 203 def handle_parser_errors yield rescue OptionParser::MissingArgument => e raise Bolt::CLIError, "Option '#{e.args.first}' needs a parameter" rescue OptionParser::InvalidArgument => e raise Bolt::CLIError, "Invalid parameter specified for option '#{e.args.first}': #{e.args[1]}" rescue OptionParser::InvalidOption, OptionParser::AmbiguousOption => e raise Bolt::CLIError, "Unknown argument '#{e.args.first}'" end |
#install_puppetfile(puppetfile, modulepath) ⇒ Object
410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 |
# File 'lib/bolt/cli.rb', line 410 def install_puppetfile(puppetfile, modulepath) require 'r10k/action/puppetfile/install' require 'bolt/r10k_log_proxy' if puppetfile.exist? moduledir = modulepath.first.to_s r10k_config = { root: puppetfile.dirname.to_s, puppetfile: puppetfile.to_s, moduledir: moduledir } install_action = R10K::Action::Puppetfile::Install.new(r10k_config, nil) # Override the r10k logger with a proxy to our own logger R10K::Logging.instance_variable_set(:@outputter, Bolt::R10KLogProxy.new) ok = install_action.call outputter.print_puppetfile_result(ok, puppetfile, moduledir) ok ? 0 : 1 else raise Bolt::FileError.new("Could not find a Puppetfile at #{puppetfile}", puppetfile) end rescue R10K::Error => e raise PuppetfileError, e end |
#list_modules ⇒ Object
406 407 408 |
# File 'lib/bolt/cli.rb', line 406 def list_modules outputter.print_module_list(pal.list_modules) end |
#list_plans ⇒ Object
356 357 358 |
# File 'lib/bolt/cli.rb', line 356 def list_plans outputter.print_plans(pal.list_plans, pal.list_modulepath) end |
#list_tasks ⇒ Object
348 349 350 |
# File 'lib/bolt/cli.rb', line 348 def list_tasks outputter.print_tasks(pal.list_tasks, pal.list_modulepath) end |
#outputter ⇒ Object
467 468 469 |
# File 'lib/bolt/cli.rb', line 467 def outputter @outputter ||= Bolt::Outputter.for_format(config.format, config.color, config.trace) end |
#pal ⇒ Object
437 438 439 |
# File 'lib/bolt/cli.rb', line 437 def pal @pal ||= Bolt::PAL.new(config.modulepath, config.hiera_config, config.compile_concurrency) end |
#parse ⇒ Object
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 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 |
# File 'lib/bolt/cli.rb', line 70 def parse parser = BoltOptionParser.new() # This part aims to handle both `bolt <mode> --help` and `bolt help <mode>`. remaining = handle_parser_errors { parser.permute(@argv) } unless @argv.empty? if @argv.empty? || help?(parser, remaining) puts parser.help raise Bolt::CLIExit end # This section handles parsing non-flag options which are # subcommand specific rather then part of the config actions = COMMANDS[[:subcommand]] if actions && !actions.empty? [:action] = remaining.shift end [:object] = remaining.shift , remaining = remaining.partition { |s| s =~ /.+=/ } if [:task_options] unless .empty? raise Bolt::CLIError, "Parameters must be specified through either the --params " \ "option or param=value pairs, not both" end [:params_parsed] = true else [:params_parsed] = false [:task_options] = Hash[.map { |a| a.split('=', 2) }] end [:leftovers] = remaining validate() @config = if [:configfile] Bolt::Config.from_file([:configfile], ) else boltdir = if [:boltdir] Bolt::Boltdir.new([:boltdir]) else Bolt::Boltdir.find_boltdir(Dir.pwd) end Bolt::Config.from_boltdir(boltdir, ) end Bolt::Logger.configure(config.log, config.color) # After validation, initialize inventory and targets. Errors here are better to catch early. unless [:subcommand] == 'puppetfile' || [:action] == 'show' if [:query] if [:nodes].any? raise Bolt::CLIError, "Only one of '--nodes' or '--query' may be specified" end nodes = query_puppetdb_nodes([:query]) [:targets] = inventory.get_targets(nodes) [:nodes] = nodes if [:subcommand] == 'plan' else [:targets] = inventory.get_targets([:nodes]) end end rescue Bolt::Error => e warn e. raise e end |
#puppetdb_client ⇒ Object
213 214 215 216 217 |
# File 'lib/bolt/cli.rb', line 213 def puppetdb_client return @puppetdb_client if @puppetdb_client puppetdb_config = Bolt::PuppetDB::Config.load_config(nil, config.puppetdb) @puppetdb_client = Bolt::PuppetDB::Client.new(puppetdb_config) end |
#query_puppetdb_nodes(query) ⇒ Object
219 220 221 |
# File 'lib/bolt/cli.rb', line 219 def query_puppetdb_nodes(query) puppetdb_client.query_certnames(query) end |
#run_plan(plan_name, plan_arguments, nodes, options) ⇒ Object
360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 |
# File 'lib/bolt/cli.rb', line 360 def run_plan(plan_name, plan_arguments, nodes, ) unless nodes.empty? if plan_arguments['nodes'] raise Bolt::CLIError, "A plan's 'nodes' parameter may be specified using the --nodes option, but in that " \ "case it must not be specified as a separate nodes=<value> parameter nor included " \ "in the JSON data passed in the --params option" end plan_arguments['nodes'] = nodes.join(',') end params = [:noop] ? plan_arguments.merge('_noop' => true) : plan_arguments plan_context = { plan_name: plan_name, params: params } plan_context[:description] = [:description] if [:description] executor = Bolt::Executor.new(config.concurrency, @analytics, [:noop], bundled_content: bundled_content) executor.start_plan(plan_context) result = pal.run_plan(plan_name, plan_arguments, executor, inventory, puppetdb_client) # If a non-bolt exception bubbles up the plan won't get finished executor.finish_plan(result) outputter.print_plan_result(result) result.ok? ? 0 : 1 end |
#show_plan(plan_name) ⇒ Object
352 353 354 |
# File 'lib/bolt/cli.rb', line 352 def show_plan(plan_name) outputter.print_plan_info(pal.get_plan_info(plan_name)) end |
#show_task(task_name) ⇒ Object
344 345 346 |
# File 'lib/bolt/cli.rb', line 344 def show_task(task_name) outputter.print_task_info(pal.get_task_info(task_name)) end |
#validate(options) ⇒ Object
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 |
# File 'lib/bolt/cli.rb', line 138 def validate() unless COMMANDS.include?([:subcommand]) raise Bolt::CLIError, "Expected subcommand '#{[:subcommand]}' to be one of " \ "#{COMMANDS.keys.join(', ')}" end actions = COMMANDS[[:subcommand]] if actions.any? if [:action].nil? raise Bolt::CLIError, "Expected an action of the form 'bolt #{[:subcommand]} <action>'" end unless actions.include?([:action]) raise Bolt::CLIError, "Expected action '#{[:action]}' to be one of " \ "#{actions.join(', ')}" end end if [:subcommand] != 'file' && [:subcommand] != 'script' && ![:leftovers].empty? raise Bolt::CLIError, "Unknown argument(s) #{[:leftovers].join(', ')}" end if %w[task plan].include?([:subcommand]) && [:action] == 'run' if [:object].nil? raise Bolt::CLIError, "Must specify a #{[:subcommand]} to run" end # This may mean that we parsed a parameter as the object unless [:object] =~ /\A([a-z][a-z0-9_]*)?(::[a-z][a-z0-9_]*)*\Z/ raise Bolt::CLIError, "Invalid #{[:subcommand]} '#{[:object]}'" end end if !%w[plan puppetfile].include?([:subcommand]) && [:action] != 'show' if [:nodes].empty? && [:query].nil? raise Bolt::CLIError, "Targets must be specified with '--nodes' or '--query'" elsif [:nodes].any? && [:query] raise Bolt::CLIError, "Only one of '--nodes' or '--query' may be specified" end end if [:boltdir] && [:configfile] raise Bolt::CLIError, "Only one of '--boltdir' or '--configfile' may be specified" end if [:noop] && !([:subcommand] == 'task' && [:action] == 'run') && [:subcommand] != 'apply' raise Bolt::CLIError, "Option '--noop' may only be specified when running a task or applying manifest code" end if [:subcommand] == 'apply' && ([:object] && [:code]) raise Bolt::CLIError, "--execute is unsupported when specifying a manifest file" end if [:subcommand] == 'apply' && (![:object] && ![:code]) raise Bolt::CLIError, "a manifest file or --execute is required" end end |
#validate_file(type, path, allow_dir = false) ⇒ Object
441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 |
# File 'lib/bolt/cli.rb', line 441 def validate_file(type, path, allow_dir = false) if path.nil? raise Bolt::CLIError, "A #{type} must be specified" end stat = file_stat(path) if !stat.readable? raise Bolt::FileError.new("The #{type} '#{path}' is unreadable", path) elsif !stat.file? && (!allow_dir || !stat.directory?) expected = allow_dir ? 'file or directory' : 'file' raise Bolt::FileError.new("The #{type} '#{path}' is not a #{expected}", path) elsif stat.directory? Dir.foreach(path) do |file| next if %w[. ..].include?(file) validate_file(type, File.join(path, file), allow_dir) end end rescue Errno::ENOENT raise Bolt::FileError.new("The #{type} '#{path}' does not exist", path) end |