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 convert], 'file' => %w[upload], 'puppetfile' => %w[install show-modules generate-types], 'secret' => %w[encrypt decrypt createkeys], 'inventory' => %w[show], 'group' => %w[show], 'project' => %w[init migrate], '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
- #analytics ⇒ Object
- #apply_manifest(code, targets, filename = nil, noop = false) ⇒ Object
- #bundled_content ⇒ Object
- #config_loaded ⇒ Object
- #convert_plan(plan) ⇒ Object
- #execute(options) ⇒ Object
- #generate_types ⇒ Object
- #handle_parser_errors ⇒ Object
-
#incomplete_install? ⇒ Boolean
Gem installs include the aggregate, canary, and puppetdb_fact modules, while package installs include modules listed in the Bolt repo Puppetfile.
-
#initialize(argv) ⇒ CLI
constructor
A new instance of CLI.
-
#initialize_project ⇒ Object
Initializes a specified directory as a Bolt project and installs any modules specified by the user, along with their dependencies.
- #install_puppetfile(config, puppetfile, modulepath) ⇒ Object
- #list_groups ⇒ Object
- #list_modules ⇒ Object
- #list_plans ⇒ Object
- #list_targets ⇒ Object
- #list_tasks ⇒ Object
- #log_outputter ⇒ Object
-
#migrate_group(group) ⇒ Object
Walks an inventory hash and replaces all ‘nodes’ keys with ‘targets’ keys and all ‘name’ keys nested in a ‘targets’ hash with ‘uri’ keys.
- #migrate_project ⇒ Object
- #outputter ⇒ Object
- #pal ⇒ Object
- #parse ⇒ Object
- #plugins ⇒ Object
- #puppetdb_client ⇒ Object
- #query_puppetdb_nodes(query) ⇒ Object
- #rerun ⇒ Object
-
#resolve_puppetfile_specs ⇒ Object
Resolves Puppetfile specs from user-specified modules and dependencies resolved by the puppetfile-resolver gem.
- #run_plan(plan_name, plan_arguments, nodes, options) ⇒ Object
- #show_plan(plan_name) ⇒ Object
- #show_targets ⇒ Object
- #show_task(task_name) ⇒ Object
- #update_targets(options) ⇒ Object
- #validate(options) ⇒ Object
- #validate_file(type, path, allow_dir = false) ⇒ Object
- #warn_inventory_overrides_cli(opts) ⇒ Object
Constructor Details
Instance Attribute Details
#config ⇒ Object (readonly)
Returns the value of attribute config.
43 44 45 |
# File 'lib/bolt/cli.rb', line 43 def config @config end |
#options ⇒ Object (readonly)
Returns the value of attribute options.
43 44 45 |
# File 'lib/bolt/cli.rb', line 43 def @options end |
Instance Method Details
#analytics ⇒ Object
808 809 810 811 812 813 814 |
# File 'lib/bolt/cli.rb', line 808 def analytics @analytics ||= begin client = Bolt::Analytics.build_client client.bundled_content = bundled_content client end end |
#apply_manifest(code, targets, filename = nil, noop = false) ⇒ Object
536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 |
# File 'lib/bolt/cli.rb', line 536 def apply_manifest(code, targets, filename = nil, noop = false) Puppet[:tasks] = false ast = pal.parse_manifest(code, filename) if defined?(ast.body) && (ast.body.is_a?(Puppet::Pops::Model::HostClassDefinition) || ast.body.is_a?(Puppet::Pops::Model::ResourceTypeDefinition)) = "Manifest only contains definitions and will result in no changes on the targets. "\ "Definitions must be declared for their resources to be applied. You can read more "\ "about defining and declaring classes and types in the Puppet documentation at "\ "https://puppet.com/docs/puppet/latest/lang_classes.html and "\ "https://puppet.com/docs/puppet/latest/lang_defined_types.html" @logger.warn() end executor = Bolt::Executor.new(config.concurrency, analytics, noop) executor.subscribe(outputter) if .fetch(:format, 'human') == 'human' executor.subscribe(log_outputter) # apply logging looks like plan logging, so tell the outputter we're in a # plan even though we're not executor.publish_event(type: :plan_start, plan: nil) results = nil elapsed_time = Benchmark.realtime do 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 end executor.shutdown outputter.print_apply_result(results, elapsed_time) rerun.update(results) results.ok ? 0 : 1 end |
#bundled_content ⇒ Object
816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 |
# File 'lib/bolt/cli.rb', line 816 def bundled_content # If the bundled content directory is empty, Bolt is likely installed as a gem. if ENV['BOLT_GEM'].nil? && incomplete_install? msg = <<~MSG.chomp Bolt may be installed as a gem. To use Bolt reliably and with all of its dependencies, uninstall the 'bolt' gem and install Bolt as a package: https://puppet.com/docs/bolt/latest/bolt_installing.html If you meant to install Bolt as a gem and want to disable this warning, set the BOLT_GEM environment variable. MSG @logger.warn(msg) end # We only need to enumerate bundled content when running a task or plan content = { 'Plan' => [], 'Task' => [], 'Plugin' => Bolt::Plugin::BUILTIN_PLUGINS } if %w[plan task].include?([:subcommand]) && [:action] == 'run' default_content = Bolt::PAL.new([], nil, nil) content['Plan'] = default_content.list_plans.each_with_object([]) do |iter, col| col << iter&.first end content['Task'] = default_content.list_tasks.each_with_object([]) do |iter, col| col << iter&.first end end content end |
#config_loaded ⇒ Object
848 849 850 851 852 853 |
# File 'lib/bolt/cli.rb', line 848 def config_loaded msg = <<~MSG.chomp Loaded configuration from: '#{config.config_files.join("', '")}' MSG @logger.debug(msg) end |
#convert_plan(plan) ⇒ Object
784 785 786 |
# File 'lib/bolt/cli.rb', line 784 def convert_plan(plan) pal.convert_plan(plan) end |
#execute(options) ⇒ Object
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 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 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 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 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 436 437 438 439 440 441 442 443 444 445 446 447 |
# File 'lib/bolt/cli.rb', line 299 def execute() = nil handler = Signal.trap :INT do |signo| @logger.info( "Exiting after receiving SIG#{Signal.signame(signo)} signal.#{ ? ' ' + : ''}" ) exit! end if [:action] == 'convert' convert_plan([:object]) return 0 end screen = "#{[:subcommand]}_#{[:action]}" # submit a different screen for `bolt task show` and `bolt task show foo` if [:action] == 'show' && [:object] screen += '_object' end screen_view_fields = { output_format: config.format, # For continuity boltdir_type: config.project.type } # Only include target and inventory info for commands that take a targets # list. This avoids loading inventory for commands that don't need it. if .key?(:targets) screen_view_fields.merge!(target_nodes: [:targets].count, inventory_nodes: inventory.node_names.count, inventory_groups: inventory.group_names.count, inventory_version: inventory.version) end analytics.screen_view(screen, screen_view_fields) 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 elsif [:subcommand] == 'inventory' if [:detail] show_targets else list_targets end elsif [:subcommand] == 'group' list_groups 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 'project' if [:action] == 'init' code = initialize_project elsif [:action] == 'migrate' code = migrate_project end when 'plan' code = run_plan([:object], [:task_options], [:target_args], ) when 'puppetfile' if [:action] == 'generate-types' code = generate_types elsif [:action] == 'install' code = install_puppetfile(@config.puppetfile_config, @config.puppetfile, @config.modulepath) end when 'secret' code = Bolt::Secret.execute(plugins, outputter, ) 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]) targets = [:targets] results = nil outputter.print_head elapsed_time = Benchmark.realtime do executor_opts = {} executor_opts[:description] = [:description] if .key?(:description) executor.subscribe(outputter) executor.subscribe(log_outputter) results = case [:subcommand] when 'command' executor.run_command(targets, [:object], executor_opts) when 'script' script = [:object] validate_file('script', script) executor.run_script(targets, script, [:leftovers], executor_opts) when 'task' pal.run_task([:object], targets, [:task_options], executor, inventory, [:description]) 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) end end executor.shutdown rerun.update(results) 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 |
#generate_types ⇒ Object
580 581 582 583 584 |
# File 'lib/bolt/cli.rb', line 580 def generate_types # generate_types will surface a nice error with helpful message if it fails pal.generate_types 0 end |
#handle_parser_errors ⇒ Object
250 251 252 253 254 255 256 257 258 |
# File 'lib/bolt/cli.rb', line 250 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 |
#incomplete_install? ⇒ Boolean
Gem installs include the aggregate, canary, and puppetdb_fact modules, while package installs include modules listed in the Bolt repo Puppetfile
857 858 859 |
# File 'lib/bolt/cli.rb', line 857 def incomplete_install? (Dir.children(Bolt::PAL::MODULES_PATH) - %w[aggregate canary puppetdb_fact]).empty? end |
#initialize_project ⇒ Object
Initializes a specified directory as a Bolt project and installs any modules specified by the user, along with their dependencies
588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 |
# File 'lib/bolt/cli.rb', line 588 def initialize_project project = Pathname.new(File.([:object] || Dir.pwd)) config = project + 'bolt.yaml' puppetfile = project + 'Puppetfile' modulepath = [project + 'modules'] # If modules were specified, first check if there is already a Puppetfile at the project # directory, erroring if there is. If there is no Puppetfile, generate the Puppetfile # content by resolving the specified modules and all their dependencies. # We generate the Puppetfile first so that any errors in resolving modules and their # dependencies are caught early and do not create a project directory. if [:modules] if puppetfile.exist? raise Bolt::CLIError, "Found existing Puppetfile at #{puppetfile}, unable to initialize project with "\ "#{[:modules].join(', ')}" else puppetfile_specs = resolve_puppetfile_specs end end # Warn the user if the project directory already exists. We don't error here since users # might not have installed any modules yet. if config.exist? @logger.warn "Found existing project directory at #{project}" end # Create the project directory FileUtils.mkdir_p(project) # Bless the project directory as a...wait for it...project if FileUtils.touch(config) outputter. "Successfully created Bolt project at #{project}" else raise Bolt::FileError.new("Could not create Bolt project directory at #{project}", nil) end # Write the generated Puppetfile to the fancy new project if puppetfile_specs File.write(puppetfile, puppetfile_specs.join("\n")) outputter. "Successfully created Puppetfile at #{puppetfile}" # Install the modules from our shiny new Puppetfile if install_puppetfile({}, puppetfile, modulepath) outputter. "Successfully installed #{[:modules].join(', ')}" else raise Bolt::CLIError, "Could not install #{[:modules].join(', ')}" end end 0 end |
#install_puppetfile(config, puppetfile, modulepath) ⇒ Object
741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 |
# File 'lib/bolt/cli.rb', line 741 def install_puppetfile(config, puppetfile, modulepath) require 'r10k/cli' require 'bolt/r10k_log_proxy' if puppetfile.exist? moduledir = modulepath.first.to_s r10k_opts = { root: puppetfile.dirname.to_s, puppetfile: puppetfile.to_s, moduledir: moduledir } settings = R10K::Settings.global_settings.evaluate(config) R10K::Initializers::GlobalInitializer.new(settings).call install_action = R10K::Action::Puppetfile::Install.new(r10k_opts, 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) # Automatically generate types after installing modules pal.generate_types 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_groups ⇒ Object
481 482 483 484 |
# File 'lib/bolt/cli.rb', line 481 def list_groups groups = inventory.group_names outputter.print_groups(groups) end |
#list_modules ⇒ Object
576 577 578 |
# File 'lib/bolt/cli.rb', line 576 def list_modules outputter.print_module_list(pal.list_modules) end |
#list_plans ⇒ Object
464 465 466 467 468 469 |
# File 'lib/bolt/cli.rb', line 464 def list_plans plans = pal.list_plans plans.select! { |plan| plan.first.include?([:filter]) } if [:filter] plans.select! { |plan| config.project.plans.include?(plan.first) } unless config.project.plans.nil? outputter.print_plans(plans, pal.list_modulepath) end |
#list_targets ⇒ Object
471 472 473 474 |
# File 'lib/bolt/cli.rb', line 471 def list_targets update_targets() outputter.print_targets([:targets]) end |
#list_tasks ⇒ Object
453 454 455 456 457 458 |
# File 'lib/bolt/cli.rb', line 453 def list_tasks tasks = pal.list_tasks tasks.select! { |task| task.first.include?([:filter]) } if [:filter] tasks.select! { |task| config.project.tasks.include?(task.first) } unless config.project.tasks.nil? outputter.print_tasks(tasks, pal.list_modulepath) end |
#log_outputter ⇒ Object
804 805 806 |
# File 'lib/bolt/cli.rb', line 804 def log_outputter @log_outputter ||= Bolt::Outputter::Logger.new([:verbose], config.trace) end |
#migrate_group(group) ⇒ Object
Walks an inventory hash and replaces all ‘nodes’ keys with ‘targets’ keys and all ‘name’ keys nested in a ‘targets’ hash with ‘uri’ keys. Data is modified in place.
723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 |
# File 'lib/bolt/cli.rb', line 723 def migrate_group(group) migrated = false if group.key?('nodes') migrated = true targets = group['nodes'].map do |target| target['uri'] = target.delete('name') if target.is_a?(Hash) target end group.delete('nodes') group['targets'] = targets end (group['groups'] || []).each do |subgroup| migrated_group = migrate_group(subgroup) migrated ||= migrated_group end migrated end |
#migrate_project ⇒ Object
698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 |
# File 'lib/bolt/cli.rb', line 698 def migrate_project inventory_file = config.inventoryfile || config.default_inventoryfile data = Bolt::Util.read_yaml_hash(inventory_file, 'inventory') data.delete('version') if data['version'] != 2 migrated = migrate_group(data) ok = File.write(inventory_file, data.to_yaml) if migrated result = if migrated && ok "Successfully migrated Bolt project to latest version." elsif !migrated "Bolt project already on latest version. Nothing to do." else "Could not migrate Bolt project to latest version." end outputter. result ok ? 0 : 1 end |
#outputter ⇒ Object
800 801 802 |
# File 'lib/bolt/cli.rb', line 800 def outputter @outputter ||= Bolt::Outputter.for_format(config.format, config.color, [:verbose], config.trace) end |
#pal ⇒ Object
773 774 775 776 777 778 779 780 781 782 |
# File 'lib/bolt/cli.rb', line 773 def pal project = config.project.load_as_module? ? config.project : nil @pal ||= Bolt::PAL.new(config.modulepath, config.hiera_config, config.project.resource_types, config.compile_concurrency, config.trusted_external, config.apply_settings, project) end |
#parse ⇒ Object
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 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 |
# File 'lib/bolt/cli.rb', line 79 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?(remaining) # Update the parser for the subcommand (or lack thereof) parser.update puts parser.help raise Bolt::CLIExit end [:object] = remaining.shift # Only parse task_options for task or plan if %w[task plan].include?([:subcommand]) , 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 elsif .any? [:params_parsed] = false [:task_options] = Hash[.map { |a| a.split('=', 2) }] else [:params_parsed] = true [:task_options] = {} end end [:leftovers] = remaining validate() @config = if [:configfile] Bolt::Config.from_file([:configfile], ) else project = if [:boltdir] Bolt::Project.new([:boltdir]) else Bolt::Project.find_boltdir(Dir.pwd) end Bolt::Config.from_project(project, ) end Bolt::Logger.configure(config.log, config.color) # Logger must be configured before checking path case and project file, otherwise warnings will not display @config.check_path_case('modulepath', @config.modulepath) @config.project.check_deprecated_file # Log the file paths for loaded config files config_loaded # Display warnings created during parser and config initialization parser.warnings.each { |warning| @logger.warn(warning[:msg]) } config.warnings.each { |warning| @logger.warn(warning[:msg]) } # After validation, initialize inventory and targets. Errors here are better to catch early. # After this step # options[:target_args] will contain a string/array version of the targetting options this is passed to plans # options[:targets] will contain a resolved set of Target objects unless [:subcommand] == 'puppetfile' || [:subcommand] == 'secret' || [:subcommand] == 'project' || [:action] == 'show' || [:action] == 'convert' update_targets() end unless .key?(:verbose) # Default to verbose for everything except plans [:verbose] = [:subcommand] != 'plan' end warn_inventory_overrides_cli() rescue Bolt::Error => e outputter.fatal_error(e) raise e end |
#plugins ⇒ Object
264 265 266 |
# File 'lib/bolt/cli.rb', line 264 def plugins @plugins ||= Bolt::Plugin.setup(config, pal, analytics) end |
#puppetdb_client ⇒ Object
260 261 262 |
# File 'lib/bolt/cli.rb', line 260 def puppetdb_client plugins.puppetdb_client end |
#query_puppetdb_nodes(query) ⇒ Object
268 269 270 |
# File 'lib/bolt/cli.rb', line 268 def query_puppetdb_nodes(query) puppetdb_client.query_certnames(query) end |
#rerun ⇒ Object
796 797 798 |
# File 'lib/bolt/cli.rb', line 796 def rerun @rerun ||= Bolt::Rerun.new(@config.rerunfile, @config.save_rerun) end |
#resolve_puppetfile_specs ⇒ Object
Resolves Puppetfile specs from user-specified modules and dependencies resolved by the puppetfile-resolver gem.
642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 |
# File 'lib/bolt/cli.rb', line 642 def resolve_puppetfile_specs require 'puppetfile-resolver' # Build the document model from the module names, defaulting to the latest version of each module model = PuppetfileResolver::Puppetfile::Document.new('') [:modules].each do |mod_name| model.add_module( PuppetfileResolver::Puppetfile::ForgeModule.new(mod_name).tap { |mod| mod.version = :latest } ) end # Make sure the Puppetfile model is valid unless model.valid? raise Bolt::ValidationError, "Unable to resolve dependencies for #{[:modules].join(', ')}" end # Create the resolver using the Puppetfile model. nil disables Puppet version restrictions. resolver = PuppetfileResolver::Resolver.new(model, nil) # Configure and resolve the dependency graph result = resolver.resolve( cache: nil, ui: nil, module_paths: [], allow_missing_modules: true ) # Validate that the modules exist missing_graph = result.specifications.select do |_name, spec| spec.instance_of? PuppetfileResolver::Models::MissingModuleSpecification end if missing_graph.any? titles = model.modules.each_with_object({}) do |mod, acc| acc[mod.name] = mod.title end names = titles.values_at(*missing_graph.keys) plural = names.count == 1 ? '' : 's' raise Bolt::ValidationError, "Unknown module name#{plural} #{names.join(', ')}" end # Filter the dependency graph to only include module specifications spec_graph = result.specifications.select do |_name, spec| spec.instance_of? PuppetfileResolver::Models::ModuleSpecification end # Map specification models to a Puppetfile specification spec_graph.values.map do |spec| "mod '#{spec.owner}-#{spec.name}', '#{spec.version}'" end end |
#run_plan(plan_name, plan_arguments, nodes, options) ⇒ Object
486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 |
# File 'lib/bolt/cli.rb', line 486 def run_plan(plan_name, plan_arguments, nodes, ) unless nodes.empty? if plan_arguments['nodes'] || plan_arguments['targets'] key = plan_arguments.include?('nodes') ? 'nodes' : 'targets' raise Bolt::CLIError, "A plan's '#{key}' parameter may be specified using the --#{key} option, but in that " \ "case it must not be specified as a separate #{key}=<value> parameter nor included " \ "in the JSON data passed in the --params option" end plan_params = pal.get_plan_info(plan_name)['parameters'] target_param = plan_params.dig('targets', 'type') =~ /TargetSpec/ node_param = plan_params.include?('nodes') if node_param && target_param msg = "Plan parameters include both 'nodes' and 'targets' with type 'TargetSpec', " \ "neither will populated with the value for --nodes or --targets." @logger.warn(msg) elsif node_param plan_arguments['nodes'] = nodes.join(',') elsif target_param plan_arguments['targets'] = nodes.join(',') end end plan_context = { plan_name: plan_name, params: plan_arguments } plan_context[:description] = [:description] if [:description] executor = Bolt::Executor.new(config.concurrency, analytics, [:noop]) if .fetch(:format, 'human') == 'human' executor.subscribe(outputter) else # Only subscribe to out::message events for JSON outputter executor.subscribe(outputter, [:message]) end executor.subscribe(log_outputter) 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) executor.shutdown rerun.update(result) outputter.print_plan_result(result) result.ok? ? 0 : 1 end |
#show_plan(plan_name) ⇒ Object
460 461 462 |
# File 'lib/bolt/cli.rb', line 460 def show_plan(plan_name) outputter.print_plan_info(pal.get_plan_info(plan_name)) end |
#show_targets ⇒ Object
476 477 478 479 |
# File 'lib/bolt/cli.rb', line 476 def show_targets update_targets() outputter.print_target_info([:targets]) end |
#show_task(task_name) ⇒ Object
449 450 451 |
# File 'lib/bolt/cli.rb', line 449 def show_task(task_name) outputter.print_task_info(pal.get_task(task_name)) end |
#update_targets(options) ⇒ Object
163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 |
# File 'lib/bolt/cli.rb', line 163 def update_targets() target_opts = .keys.select { |opt| %i[query rerun targets].include?(opt) } target_string = "'--targets', '--rerun', or '--query'" if target_opts.length > 1 raise Bolt::CLIError, "Only one targeting option #{target_string} may be specified" elsif target_opts.empty? && [:subcommand] != 'plan' raise Bolt::CLIError, "Command requires a targeting option: #{target_string}" end targets = if [:query] query_puppetdb_nodes([:query]) elsif [:rerun] rerun.get_targets([:rerun]) else [:targets] || [] end [:target_args] = targets [:targets] = inventory.get_targets(targets) end |
#validate(options) ⇒ Object
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 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 |
# File 'lib/bolt/cli.rb', line 183 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 [: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 if [:subcommand] == 'command' && (![:object] || [:object].empty?) raise Bolt::CLIError, "Must specify a command to run" end if [:subcommand] == 'secret' && ([:action] == 'decrypt' || [:action] == 'encrypt') && ![:object] raise Bolt::CLIError, "Must specify a value to #{[:action]}" end end |
#validate_file(type, path, allow_dir = false) ⇒ Object
788 789 790 791 792 793 794 |
# File 'lib/bolt/cli.rb', line 788 def validate_file(type, path, allow_dir = false) if path.nil? raise Bolt::CLIError, "A #{type} must be specified" end Bolt::Util.validate_file(type, path, allow_dir) end |
#warn_inventory_overrides_cli(opts) ⇒ Object
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 |
# File 'lib/bolt/cli.rb', line 272 def warn_inventory_overrides_cli(opts) inventory_source = if ENV[Bolt::Inventory::ENVIRONMENT_VAR] Bolt::Inventory::ENVIRONMENT_VAR elsif @config.inventoryfile && Bolt::Util.file_stat(@config.inventoryfile) @config.inventoryfile else begin Bolt::Util.file_stat(@config.default_inventoryfile) @config.default_inventoryfile rescue Errno::ENOENT nil end end inventory_cli_opts = %i[authentication escalation transports].each_with_object([]) do |key, acc| acc.concat(Bolt::BoltOptionParser::OPTIONS[key]) end inventory_cli_opts.concat(%w[no-host-key-check no-ssl no-ssl-verify no-tty]) = Set.new(opts.keys.map(&:to_s)).intersection(inventory_cli_opts) if inventory_source && .any? @logger.warn("CLI arguments #{.to_a} may be overridden by Inventory: #{inventory_source}") end end |