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 new], 'file' => %w[download 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[], 'guide' => %w[], 'module' => %w[install] }.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
- #execute(options) ⇒ Object
-
#fatal_error(error) ⇒ Object
Mimicks the output from Outputter::Human#fatal_error.
-
#finalize_setup ⇒ Object
Completes the setup process by configuring Bolt and log messages.
- #generate_types ⇒ Object
-
#guides ⇒ Object
Collects the list of Bolt guides and maps them to their topics.
- #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_modules(puppetfile_path, config, moduledir, modules) ⇒ Object
Installs modules declared in the project configuration file.
-
#install_project_modules ⇒ Object
Installs modules declared in the project configuration file.
-
#install_puppetfile(config, puppetfile, moduledir) ⇒ Object
Loads a Puppetfile and installs its modules.
- #list_groups ⇒ Object
- #list_modules ⇒ Object
- #list_plans ⇒ Object
- #list_targets ⇒ Object
- #list_tasks ⇒ Object
-
#list_topics ⇒ Object
Display the list of available Bolt guides.
-
#load_config ⇒ Object
Loads the project and configuration.
- #log_outputter ⇒ Object
- #new_plan(plan_name) ⇒ Object
- #outputter ⇒ Object
- #pal ⇒ Object
-
#parse ⇒ Object
Wrapper method that is called by the Bolt executable.
-
#parse_command ⇒ Object
Parses the command and validates options.
- #plugins ⇒ Object
- #puppetdb_client ⇒ Object
- #query_puppetdb_nodes(query) ⇒ Object
- #rerun ⇒ Object
- #run_plan(plan_name, plan_arguments, nodes, options) ⇒ Object
-
#show_guide(topic) ⇒ Object
Display a specific Bolt guide.
- #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
#initialize(argv) ⇒ CLI
Returns a new instance of CLI.
48 49 50 51 52 53 |
# File 'lib/bolt/cli.rb', line 48 def initialize(argv) Bolt::Logger.initialize_logging @logger = Bolt::Logger.logger(self) @argv = argv = {} end |
Instance Attribute Details
#config ⇒ Object (readonly)
Returns the value of attribute config.
46 47 48 |
# File 'lib/bolt/cli.rb', line 46 def config @config end |
#options ⇒ Object (readonly)
Returns the value of attribute options.
46 47 48 |
# File 'lib/bolt/cli.rb', line 46 def end |
Instance Method Details
#analytics ⇒ Object
1002 1003 1004 1005 1006 1007 1008 |
# File 'lib/bolt/cli.rb', line 1002 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
737 738 739 740 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 772 773 774 775 |
# File 'lib/bolt/cli.rb', line 737 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, config.modified_concurrency) 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
1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 |
# File 'lib/bolt/cli.rb', line 1010 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 = " Bolt may be installed as a gem. To use Bolt reliably and with all of its\n dependencies, uninstall the 'bolt' gem and install Bolt as a package:\n https://puppet.com/docs/bolt/latest/bolt_installing.html\n\n If you meant to install Bolt as a gem and want to disable this warning,\n set the BOLT_GEM environment variable.\n MSG\n\n @logger.warn(msg)\n end\n\n # We only need to enumerate bundled content when running a task or plan\n content = { 'Plan' => [],\n 'Task' => [],\n 'Plugin' => Bolt::Plugin::BUILTIN_PLUGINS }\n if %w[plan task].include?(options[:subcommand]) && options[:action] == 'run'\n default_content = Bolt::PAL.new([], nil, nil)\n content['Plan'] = default_content.list_plans.each_with_object([]) do |iter, col|\n col << iter&.first\n end\n content['Task'] = default_content.list_tasks.each_with_object([]) do |iter, col|\n col << iter&.first\n end\n end\n\n content\nend\n".chomp |
#execute(options) ⇒ Object
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 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 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 535 536 |
# File 'lib/bolt/cli.rb', line 348 def execute() = nil handler = Signal.trap :INT do |signo| @logger.info( "Exiting after receiving SIG#{Signal.signame(signo)} signal.#{message ? ' ' + message : ''}" ) exit! end # Initialize inventory and targets. Errors here are better to catch early. # 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 %w[guide module project puppetfile secret].include?([:subcommand]) || %w[convert new show].include?([:action]) update_targets() end screen = "#{options[:subcommand]}_#{options[: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) case [:action] when 'show' case [:subcommand] when 'task' if [:object] show_task([:object]) else list_tasks end when 'plan' if [:object] show_plan([:object]) else list_plans end when 'inventory' if [:detail] show_targets else list_targets end when 'group' list_groups end return 0 when 'show-modules' list_modules return 0 when 'convert' pal.convert_plan([:object]) 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 'guide' code = if [:object] show_guide([:object]) else list_topics end when 'project' case [:action] when 'init' code = initialize_project when 'migrate' inv = config.inventoryfile path = config.project.path code = Bolt::ProjectMigrate.new(path, outputter, inv).migrate_project end when 'plan' case [:action] when 'new' code = new_plan([:object]) when 'run' code = run_plan([:object], [:task_options], [:target_args], ) end when 'module' case [:action] when 'install' code = install_project_modules end when 'puppetfile' case [:action] when 'generate-types' code = generate_types when 'install' code = install_puppetfile(config.puppetfile_config, config.puppetfile, config.modulepath.first) 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], config.modified_concurrency) targets = [:targets] results = nil outputter.print_head elapsed_time = Benchmark.realtime do executor_opts = {} executor_opts[:description] = [:description] if .key?(:description) executor_opts[:env_vars] = [:env_vars] if .key?(:env_vars) 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 src.nil? raise Bolt::CLIError, "A source path must be specified" end if dest.nil? raise Bolt::CLIError, "A destination path must be specified" end case [:action] when 'download' dest = File.(dest, Dir.pwd) executor.download_file(targets, src, dest, executor_opts) when 'upload' validate_file('source file', src, true) executor.upload_file(targets, src, dest, executor_opts) end 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 |
#fatal_error(error) ⇒ Object
Mimicks the output from Outputter::Human#fatal_error. This should be used to print errors prior to config being loaded, as the outputter relies on config being loaded.
1050 1051 1052 1053 1054 1055 1056 |
# File 'lib/bolt/cli.rb', line 1050 def fatal_error(error) if $stdout.isatty $stdout.puts("\033[31m#{error.message}\033[0m") else $stdout.puts(error.) end end |
#finalize_setup ⇒ Object
Completes the setup process by configuring Bolt and log messages
172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 |
# File 'lib/bolt/cli.rb', line 172 def finalize_setup Bolt::Logger.configure(config.log, config.color) Bolt::Logger.analytics = analytics # Logger must be configured before checking path case and project file, otherwise logs will not display config.check_path_case('modulepath', config.modulepath) config.project.check_deprecated_file # Log messages created during parser and config initialization config.logs.each { |log| @logger.send(log.keys[0], log.values[0]) } @parser_deprecations.each { |dep| Bolt::Logger.deprecation_warning(dep[:type], dep[:msg]) } config.deprecations.each { |dep| Bolt::Logger.deprecation_warning(dep[:type], dep[:msg]) } warn_inventory_overrides_cli() rescue Bolt::Error => e outputter.fatal_error(e) raise e end |
#generate_types ⇒ Object
781 782 783 784 785 |
# File 'lib/bolt/cli.rb', line 781 def generate_types # generate_types will surface a nice error with helpful message if it fails pal.generate_types 0 end |
#guides ⇒ Object
Collects the list of Bolt guides and maps them to their topics.
941 942 943 944 945 946 947 948 949 950 951 952 953 954 |
# File 'lib/bolt/cli.rb', line 941 def guides @guides ||= begin root_path = File.(File.join(__dir__, '..', '..', 'guides')) files = Dir.children(root_path).sort files.each_with_object({}) do |file, guides| next if file !~ /\.txt\z/ topic = File.basename(file, '.txt') guides[topic] = File.join(root_path, file) end rescue SystemCallError => e raise Bolt::FileError.new("#{e.message}: unable to load guides directory", root_path) end end |
#handle_parser_errors ⇒ Object
299 300 301 302 303 304 305 306 307 |
# File 'lib/bolt/cli.rb', line 299 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
1044 1045 1046 |
# File 'lib/bolt/cli.rb', line 1044 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
789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 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 847 848 849 850 851 852 853 |
# File 'lib/bolt/cli.rb', line 789 def initialize_project # Dir.pwd will return backslashes on Windows, but Pathname always uses # forward slashes to concatenate paths. This results in paths like # C:\User\Administrator/modules, which fail module install. This ensure # forward slashes in the cwd path. dir = File.(Dir.pwd) name = [:object] || File.basename(dir) if name !~ Bolt::Module::MODULE_NAME_REGEX if [:object] raise Bolt::ValidationError, "The provided project name '#{name}' is invalid; "\ "project name must begin with a lowercase letter and can include lowercase "\ "letters, numbers, and underscores." else raise Bolt::ValidationError, "The current directory name '#{name}' is an invalid "\ "project name. Please specify a name using 'bolt project init <name>'." end end project = Pathname.new(dir) old_config = project + 'bolt.yaml' config = project + 'bolt-project.yaml' puppetfile = project + 'Puppetfile' moduledir = project + 'modules' # Warn the user if the project directory already exists. We don't error # here since users might not have installed any modules yet. If both # bolt.yaml and bolt-project.yaml exist, this will just warn about # bolt-project.yaml and subsequent Bolt actions will warn about both files # existing. if config.exist? @logger.warn "Found existing project directory at #{project}. Skipping file creation." elsif old_config.exist? @logger.warn "Found existing #{old_config.basename} at #{project}. "\ "#{old_config.basename} is deprecated, please rename to #{config.basename}." end # 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, install the specified modules. The module installer will # resolve dependencies, generate a Puppetfile, and install the modules. if [:modules] if puppetfile.exist? raise Bolt::CLIError, "Found existing Puppetfile at #{puppetfile}, unable to initialize "\ "project with modules." end install_modules(puppetfile, {}, moduledir, [:modules]) end # If either bolt.yaml or bolt-project.yaml exist, the user has already # been warned and we can just finish project creation. Otherwise, create a # bolt-project.yaml with the project name in it. unless config.exist? || old_config.exist? begin content = { 'name' => name } File.write(config.to_path, content.to_yaml) outputter. "Successfully created Bolt project at #{project}" rescue StandardError => e raise Bolt::FileError.new("Could not create bolt-project.yaml at #{project}: #{e.message}", nil) end end 0 end |
#install_modules(puppetfile_path, config, moduledir, modules) ⇒ Object
Installs modules declared in the project configuration file.
874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 |
# File 'lib/bolt/cli.rb', line 874 def install_modules(puppetfile_path, config, moduledir, modules) require 'bolt/puppetfile' require 'bolt/puppetfile/installer' puppetfile = Bolt::Puppetfile.new(modules) # If the Puppetfile exists, check if it includes specs for each declared # module, erroring if there are any missing. Otherwise, resolve the # module dependencies and write a new Puppetfile. Users can forcibly # overwrite an existing Puppetfile with the '--force' option. if puppetfile_path.exist? && ![:force] outputter. "Parsing existing Puppetfile at #{puppetfile_path}" existing = Bolt::Puppetfile.parse(puppetfile_path) unless existing.modules.superset? puppetfile.modules missing_modules = puppetfile.modules - existing.modules raise Bolt::Error.new( "Puppetfile #{puppetfile_path} is missing specifications for modules: "\ "#{missing_modules.map(&:title).join(', ')}. This may not be a Puppetfile "\ "managed by Bolt. To forcibly overwrite the Puppetfile, run with the "\ "'--force' option.", 'bolt/missing-module-specs' ) end else outputter. "Resolving module dependencies, this may take a moment" puppetfile.resolve outputter. "Writing Puppetfile at #{puppetfile_path}" puppetfile.write(puppetfile_path, force: true) end outputter. "Syncing modules from #{puppetfile_path} to #{moduledir}" ok = Bolt::Puppetfile::Installer.new(config).install(puppetfile_path, moduledir) # Automatically generate types after installing modules. pal.generate_types outputter.print_puppetfile_result(ok, puppetfile_path, moduledir) ok ? 0 : 1 end |
#install_project_modules ⇒ Object
Installs modules declared in the project configuration file.
857 858 859 860 861 862 863 864 865 866 867 868 869 870 |
# File 'lib/bolt/cli.rb', line 857 def install_project_modules if config.project.modules.nil? outputter. "Project configuration file '#{config.project.project_file}' "\ "does not specify any module dependencies. Nothing to do." return 0 end install_modules( config.puppetfile, config.puppetfile_config, config.project.path + '.modules', config.project.modules ) end |
#install_puppetfile(config, puppetfile, moduledir) ⇒ Object
Loads a Puppetfile and installs its modules.
918 919 920 921 922 923 924 925 926 927 928 |
# File 'lib/bolt/cli.rb', line 918 def install_puppetfile(config, puppetfile, moduledir) require 'bolt/puppetfile/installer' ok = Bolt::Puppetfile::Installer.new(config).install(puppetfile, moduledir) # Automatically generate types after installing modules. pal.generate_types outputter.print_puppetfile_result(ok, puppetfile, moduledir) ok ? 0 : 1 end |
#list_groups ⇒ Object
570 571 572 573 |
# File 'lib/bolt/cli.rb', line 570 def list_groups groups = inventory.group_names outputter.print_groups(groups) end |
#list_modules ⇒ Object
777 778 779 |
# File 'lib/bolt/cli.rb', line 777 def list_modules outputter.print_module_list(pal.list_modules) end |
#list_plans ⇒ Object
553 554 555 556 557 558 |
# File 'lib/bolt/cli.rb', line 553 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.user_modulepath) end |
#list_targets ⇒ Object
560 561 562 563 |
# File 'lib/bolt/cli.rb', line 560 def list_targets update_targets() outputter.print_targets([:targets]) end |
#list_tasks ⇒ Object
542 543 544 545 546 547 |
# File 'lib/bolt/cli.rb', line 542 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.user_modulepath) end |
#list_topics ⇒ Object
Display the list of available Bolt guides.
957 958 959 960 |
# File 'lib/bolt/cli.rb', line 957 def list_topics outputter.print_topics(guides.keys) 0 end |
#load_config ⇒ Object
Loads the project and configuration. All errors that are raised here are not handled by the outputter, as it relies on config being loaded.
147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 |
# File 'lib/bolt/cli.rb', line 147 def load_config @config = if ENV['BOLT_PROJECT'] project = Bolt::Project.create_project(ENV['BOLT_PROJECT'], 'environment') Bolt::Config.from_project(project, ) elsif [:configfile] Bolt::Config.from_file([:configfile], ) else project = if [:boltdir] dir = Pathname.new([:boltdir]) if (dir + Bolt::Project::BOLTDIR_NAME).directory? Bolt::Project.create_project(dir + Bolt::Project::BOLTDIR_NAME) else Bolt::Project.create_project(dir) end else Bolt::Project.find_boltdir(Dir.pwd) end Bolt::Config.from_project(project, ) end rescue Bolt::Error => e fatal_error(e) raise e end |
#log_outputter ⇒ Object
998 999 1000 |
# File 'lib/bolt/cli.rb', line 998 def log_outputter @log_outputter ||= Bolt::Outputter::Logger.new([:verbose], config.trace) end |
#new_plan(plan_name) ⇒ Object
575 576 577 578 579 580 581 582 583 584 585 586 587 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 639 640 641 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 |
# File 'lib/bolt/cli.rb', line 575 def new_plan(plan_name) @logger.warn("Command 'bolt plan new' is experimental and subject to changes.") if config.project.name.nil? raise Bolt::Error.new( "Project directory '#{config.project.path}' is not a named project. Unable to create "\ "a project-level plan. To name a project, set the 'name' key in the 'bolt-project.yaml' "\ "configuration file.", "bolt/unnamed-project-error" ) end if plan_name !~ Bolt::Module::CONTENT_NAME_REGEX = " Invalid plan name '\#{plan_name}'. Plan names are composed of one or more name segments\n separated by double colons '::'.\n \n Each name segment must begin with a lowercase letter, and may only include lowercase\n letters, digits, and underscores.\n \n Examples of valid plan names:\n - \#{config.project.name}\n - \#{config.project.name}::my_plan\n MESSAGE\n\n raise Bolt::ValidationError, message\n end\n\n prefix, *name_segments, basename = plan_name.split('::')\n\n # If the plan name is just the project name, then create an 'init' plan.\n # Otherwise, use the last name segment for the plan's filename.\n basename ||= 'init'\n\n unless prefix == config.project.name\n message = \"First segment of plan name '\#{plan_name}' must match project name '\#{config.project.name}'. \"\\\n \"Did you mean '\#{config.project.name}::\#{plan_name}'?\"\n\n raise Bolt::ValidationError, message\n end\n\n dir_path = config.project.plans_path.join(*name_segments)\n\n %w[pp yaml].each do |ext|\n next unless (path = config.project.plans_path + \"\#{basename}.\#{ext}\").exist?\n raise Bolt::Error.new(\n \"A plan with the name '\#{plan_name}' already exists at '\#{path}', nothing to do.\",\n 'bolt/existing-plan-error'\n )\n end\n\n begin\n FileUtils.mkdir_p(dir_path)\n rescue Errno::EEXIST => e\n raise Bolt::Error.new(\n \"\#{e.message}; unable to create plan directory '\#{dir_path}'\",\n 'bolt/existing-file-error'\n )\n end\n\n plan_path = dir_path + \"\#{basename}.yaml\"\n\n plan_template = <<~PLAN\n # This is the structure of a simple plan. To learn more about writing\n # YAML plans, see the documentation: http://pup.pt/bolt-yaml-plans\n\n # The description sets the description of the plan that will appear\n # in 'bolt plan show' output.\n description: A plan created with bolt plan new\n\n # The parameters key defines the parameters that can be passed to\n # the plan.\n parameters:\n targets:\n type: TargetSpec\n description: A list of targets to run actions on\n default: localhost\n\n # The steps key defines the actions the plan will take in order.\n steps:\n - message: Hello from \#{plan_name}\n - name: command_step\n command: whoami\n targets: $targets\n\n # The return key sets the return value of the plan.\n return: $command_step\n PLAN\n\n begin\n File.write(plan_path, plan_template)\n rescue Errno::EACCES => e\n raise Bolt::FileError.new(\n \"\#{e.message}; unable to create plan\",\n plan_path\n )\n end\n\n output = <<~OUTPUT\n Created plan '\#{plan_name}' at '\#{plan_path}'\n\n Show this plan with:\n bolt plan show \#{plan_name}\n Run this plan with:\n bolt plan run \#{plan_name}\n OUTPUT\n\n outputter.print_message(output)\n\n 0\nend\n".chomp |
#outputter ⇒ Object
994 995 996 |
# File 'lib/bolt/cli.rb', line 994 def outputter @outputter ||= Bolt::Outputter.for_format(config.format, config.color, [:verbose], config.trace) end |
#pal ⇒ Object
930 931 932 933 934 935 936 937 938 |
# File 'lib/bolt/cli.rb', line 930 def pal @pal ||= Bolt::PAL.new(config.modulepath, config.hiera_config, config.project.resource_types, config.compile_concurrency, config.trusted_external, config.apply_settings, config.project) end |
#parse ⇒ Object
Wrapper method that is called by the Bolt executable. Parses the command and then loads the project and config. Once config is loaded, it completes the setup process by configuring Bolt and logging messages.
This separation is needed since the Bolt::Outputter class that normally handles printing errors relies on config being loaded. All setup that happens before config is loaded will have errors printed directly to stdout, while all errors raised after config is loaded are handled by the outputter.
89 90 91 92 93 |
# File 'lib/bolt/cli.rb', line 89 def parse parse_command load_config finalize_setup end |
#parse_command ⇒ Object
Parses the command and validates options. All errors that are raised here are not handled by the outputter, as it relies on config being loaded.
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 |
# File 'lib/bolt/cli.rb', line 97 def parse_command 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 # Default to verbose for everything except plans unless .key?(:verbose) [:verbose] = [:subcommand] != 'plan' end validate() # Deprecation warnings can't be issued until after config is loaded, so # store them for later. @parser_deprecations = parser.deprecations rescue Bolt::Error => e fatal_error(e) raise e end |
#plugins ⇒ Object
313 314 315 |
# File 'lib/bolt/cli.rb', line 313 def plugins @plugins ||= Bolt::Plugin.setup(config, pal, analytics) end |
#puppetdb_client ⇒ Object
309 310 311 |
# File 'lib/bolt/cli.rb', line 309 def puppetdb_client plugins.puppetdb_client end |
#query_puppetdb_nodes(query) ⇒ Object
317 318 319 |
# File 'lib/bolt/cli.rb', line 317 def query_puppetdb_nodes(query) puppetdb_client.query_certnames(query) end |
#rerun ⇒ Object
990 991 992 |
# File 'lib/bolt/cli.rb', line 990 def rerun @rerun ||= Bolt::Rerun.new(config.rerunfile, config.save_rerun) end |
#run_plan(plan_name, plan_arguments, nodes, options) ⇒ Object
687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 |
# File 'lib/bolt/cli.rb', line 687 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], config.modified_concurrency) if %w[human rainbow].include?(.fetch(:format, '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_guide(topic) ⇒ Object
Display a specific Bolt guide.
963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 |
# File 'lib/bolt/cli.rb', line 963 def show_guide(topic) if guides[topic] analytics.event('Guide', 'known_topic', label: topic) begin guide = File.read(guides[topic]) rescue SystemCallError => e raise Bolt::FileError("#{e.message}: unable to load guide page", filepath) end outputter.print_guide(guide, topic) else analytics.event('Guide', 'unknown_topic', label: topic) outputter.("Did not find guide for topic '#{topic}'.\n\n") list_topics end 0 end |
#show_plan(plan_name) ⇒ Object
549 550 551 |
# File 'lib/bolt/cli.rb', line 549 def show_plan(plan_name) outputter.print_plan_info(pal.get_plan_info(plan_name)) end |
#show_targets ⇒ Object
565 566 567 568 |
# File 'lib/bolt/cli.rb', line 565 def show_targets update_targets() outputter.print_target_info([:targets]) end |
#show_task(task_name) ⇒ Object
538 539 540 |
# File 'lib/bolt/cli.rb', line 538 def show_task(task_name) outputter.print_task_info(pal.get_task(task_name)) end |
#update_targets(options) ⇒ Object
193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 |
# File 'lib/bolt/cli.rb', line 193 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
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 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 |
# File 'lib/bolt/cli.rb', line 213 def validate() # Disables the 'module' subcommand unless the module feature flag is set. commands = COMMANDS.dup commands.delete('module') unless ENV['BOLT_MODULE_FEATURE'] unless commands.include?([:subcommand]) raise Bolt::CLIError, "Expected subcommand '#{options[: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 #{options[:subcommand]} <action>'" end unless actions.include?([:action]) raise Bolt::CLIError, "Expected action '#{options[:action]}' to be one of " \ "#{actions.join(', ')}" end end if [:subcommand] != 'file' && [:subcommand] != 'script' && ![:leftovers].empty? raise Bolt::CLIError, "Unknown argument(s) #{options[:leftovers].join(', ')}" end if %w[task plan].include?([:subcommand]) && [:action] == 'run' if [:object].nil? raise Bolt::CLIError, "Must specify a #{options[: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 #{options[:subcommand]} '#{options[:object]}'" end end if [:boltdir] && [:configfile] raise Bolt::CLIError, "Only one of '--boltdir', '--project', 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 [:env_vars] unless %w[command script].include?([:subcommand]) && [:action] == 'run' raise Bolt::CLIError, "Option '--env-var' may only be specified when running a command or script" end 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 #{options[:action]}" end if [:subcommand] == 'plan' && [:action] == 'new' && ![:object] raise Bolt::CLIError, "Must specify a plan name." end if .key?(:debug) && .key?(:log) raise Bolt::CLIError, "Only one of '--debug' or '--log-level' may be specified" end end |
#validate_file(type, path, allow_dir = false) ⇒ Object
982 983 984 985 986 987 988 |
# File 'lib/bolt/cli.rb', line 982 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
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 |
# File 'lib/bolt/cli.rb', line 321 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 #{conflicting_options.to_a} may be overridden by Inventory: #{inventory_source}") end end |