Class: Bolt::CLI
- Inherits:
-
Object
- Object
- Bolt::CLI
- Defined in:
- lib/bolt/cli.rb
Constant Summary collapse
- BANNER =
<<-HELP.freeze Usage: bolt <subcommand> <action> [options] Available subcommands: bolt command run <command> Run a command remotely bolt script run <script> Upload a local script and run it remotely bolt task show Show list of available tasks bolt task show <task> Show documentation for task bolt task run <task> [params] Run a Puppet task bolt plan show Show list of available plans bolt plan show <plan> Show details for plan bolt plan run <plan> [params] Run a Puppet task plan bolt file upload <src> <dest> Upload a local file where [options] are: HELP
- TASK_HELP =
<<-HELP.freeze Usage: bolt task <action> <task> [options] [parameters] Available actions are: show Show list of available tasks show <task> Show documentation for task run Run a Puppet task Parameters are of the form <parameter>=<value>. Available options are: HELP
- COMMAND_HELP =
<<-HELP.freeze Usage: bolt command <action> <command> [options] Available actions are: run Run a command remotely Available options are: HELP
- SCRIPT_HELP =
<<-HELP.freeze Usage: bolt script <action> <script> [[arg1] ... [argN]] [options] Available actions are: run Upload a local script and run it remotely Available options are: HELP
- PLAN_HELP =
<<-HELP.freeze Usage: bolt plan <action> <plan> [options] [parameters] Available actions are: show Show list of available plans show <plan> Show details for plan run Run a Puppet task plan Parameters are of the form <parameter>=<value>. Available options are: HELP
- FILE_HELP =
<<-HELP.freeze Usage: bolt file <action> [options] Available actions are: upload <src> <dest> Upload local file <src> to <dest> on each node Available options are: HELP
- COMMANDS =
{ 'command' => %w[run], 'script' => %w[run], 'task' => %w[show run], 'plan' => %w[show run], 'file' => %w[upload] }.freeze
- TRANSPORTS =
%w[ssh winrm pcp].freeze
Instance Attribute Summary collapse
-
#config ⇒ Object
readonly
Returns the value of attribute config.
-
#options ⇒ Object
Returns the value of attribute options.
-
#parser ⇒ Object
readonly
Returns the value of attribute parser.
Instance Method Summary collapse
- #create_option_parser(results) ⇒ Object
- #execute(options) ⇒ Object
- #file_stat(path) ⇒ Object
- #get_arg_input(value) ⇒ Object
- #handle_parser_errors ⇒ Object
-
#initialize(argv) ⇒ CLI
constructor
A new instance of CLI.
- #outputter ⇒ Object
- #parse ⇒ Object
- #parse_params(params) ⇒ Object
- #read_arg_file(file) ⇒ Object
- #validate(options) ⇒ Object
- #validate_file(type, path) ⇒ Object
Constructor Details
#initialize(argv) ⇒ CLI
Returns a new instance of CLI.
107 108 109 110 111 112 113 114 115 116 117 118 119 120 |
# File 'lib/bolt/cli.rb', line 107 def initialize(argv) Bolt::Logger.initialize_logging @argv = argv @options = { nodes: [] } @config = Bolt::Config.new # parse mode and object, use COMMANDS as a whitelist @options[:mode] = argv[0] if COMMANDS.keys.any? { |mode| argv[0] == mode } @options[:object] = argv[1] if COMMANDS.values.flatten.uniq.any? { |object| argv[1] == object } @parser = create_option_parser(@options) @logger = Logging.logger[self] end |
Instance Attribute Details
#config ⇒ Object (readonly)
Returns the value of attribute config.
104 105 106 |
# File 'lib/bolt/cli.rb', line 104 def config @config end |
#options ⇒ Object
Returns the value of attribute options.
105 106 107 |
# File 'lib/bolt/cli.rb', line 105 def @options end |
#parser ⇒ Object (readonly)
Returns the value of attribute parser.
104 105 106 |
# File 'lib/bolt/cli.rb', line 104 def parser @parser end |
Instance Method Details
#create_option_parser(results) ⇒ Object
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 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 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 |
# File 'lib/bolt/cli.rb', line 122 def create_option_parser(results) parser = OptionParser.new('') do |opts| unless results[:mode] == 'plan' opts.on('-n', '--nodes NODES', 'Node(s) to connect to in URI format [protocol://]host[:port] (Optional)', 'Eg. --nodes bolt.puppet.com', 'Eg. --nodes localhost,ssh://nix.com:2222,winrm://windows.puppet.com', "\n", '* NODES can either be comma-separated, \'@<file>\' to read', '* nodes from a file, or \'-\' to read from stdin', '* Windows nodes must specify protocol with winrm://', '* protocol is `ssh` by default, may be `ssh` or `winrm`', '* port defaults to `22` for SSH', '* port defaults to `5985` or `5986` for WinRM, based on the --[no-]ssl setting') do |nodes| results[:nodes] << get_arg_input(nodes) end end opts.on('-u', '--user USER', "User to authenticate as (Optional)") do |user| results[:user] = user end opts.on('-p', '--password [PASSWORD]', 'Password to authenticate with (Optional).', 'Omit the value to prompt for the password.') do |password| if password.nil? STDOUT.print "Please enter your password: " results[:password] = STDIN.noecho(&:gets).chomp STDOUT.puts else results[:password] = password end end opts.on('--private-key KEY', "Private ssh key to authenticate with (Optional)") do |key| results[:key] = key end opts.on('--tmpdir DIR', "The directory to upload and execute temporary files on the target (Optional)") do |tmpdir| results[:tmpdir] = tmpdir end opts.on('-c', '--concurrency CONCURRENCY', Integer, "Maximum number of simultaneous connections " \ "(Optional, defaults to 100)") do |concurrency| results[:concurrency] = concurrency end opts.on('--connect-timeout TIMEOUT', Integer, "Connection timeout (Optional)") do |timeout| results[:connect_timeout] = timeout end opts.on('--modulepath MODULES', "List of directories containing modules, " \ "separated by #{File::PATH_SEPARATOR}") do |modulepath| results[:modulepath] = modulepath.split(File::PATH_SEPARATOR) end opts.on('--params PARAMETERS', "Parameters to a task or plan") do |params| results[:task_options] = parse_params(params) end opts.on('--format FORMAT', "Output format to use: human or json") do |format| results[:format] = format end opts.on('--[no-]host-key-check', "Check host keys with SSH") do |host_key_check| results[:host_key_check] = host_key_check end opts.on('--[no-]ssl', "Use SSL with WinRM") do |ssl| results[:ssl] = ssl end opts.on('--transport TRANSPORT', TRANSPORTS, "Specify a default transport: #{TRANSPORTS.join(', ')}") do |t| results[:transport] = t end opts.on('--run-as USER', "User to run as using privilege escalation") do |user| results[:run_as] = user end opts.on('--sudo-password [PASSWORD]', 'Password for privilege escalation') do |password| if password.nil? STDOUT.print "Please enter your privilege escalation password: " results[:sudo_password] = STDIN.noecho(&:gets).chomp STDOUT.puts else results[:sudo_password] = password end end opts.on('--configfile CONFIG_PATH', 'Specify where to load the config file from') do |path| results[:configfile] = path end opts.on('--inventoryfile INVENTORY_PATH', 'Specify where to load the invenotry file from') do |path| results[:inventoryfile] = path end opts.on_tail('--[no-]tty', "Request a pseudo TTY on nodes that support it") do |tty| results[:tty] = tty end opts.on_tail('--noop', "Execute a task that supports it in noop mode") do |_| results[:noop] = true end opts.on_tail('-h', '--help', 'Display help') do |_| results[:help] = true end opts.on_tail('--verbose', 'Display verbose logging') do |_| results[:verbose] = true end opts.on_tail('--debug', 'Display debug logging') do |_| results[:debug] = true end opts.on_tail('--version', 'Display the version') do |_| puts Bolt::VERSION raise Bolt::CLIExit end end parser. = case results[:mode] when "plan" PLAN_HELP when "command" COMMAND_HELP when "script" SCRIPT_HELP when "task" TASK_HELP when "file" FILE_HELP else BANNER end parser end |
#execute(options) ⇒ Object
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 |
# File 'lib/bolt/cli.rb', line 408 def execute() = nil handler = Signal.trap :INT do |signo| @logger.info( "Exiting after receiving SIG#{Signal.signame(signo)} signal." << ( ? ' ' << : '') ) exit! end if [:mode] == 'plan' || [:mode] == 'task' pal = Bolt::PAL.new(@config) end if [:action] == 'show' if [:mode] == 'task' if [:object] outputter.print_task_info(pal.get_task_info([:object])) else outputter.print_table(pal.list_tasks) outputter.("\nUse `bolt task show <task-name>` to view "\ "details and parameters for a specific task.") end elsif [:mode] == 'plan' if [:object] outputter.print_plan_info(pal.get_plan_info([:object])) else outputter.print_table(pal.list_plans) outputter.("\nUse `bolt plan show <plan-name>` to view "\ "details and parameters for a specific plan.") end end return 0 end = 'There may be processes left executing on some nodes.' if [:mode] == 'plan' executor = Bolt::Executor.new(@config, [:noop], true) result = pal.run_plan([:object], [:task_options], executor, inventory) outputter.print_plan_result(result) # An exception would have been raised if the plan failed code = 0 else executor = Bolt::Executor.new(@config, [:noop]) targets = [:targets] results = nil outputter.print_head elapsed_time = Benchmark.realtime do results = case [:mode] when 'command' executor.run_command(targets, [:object]) do |event| outputter.print_event(event) end when 'script' script = [:object] validate_file('script', script) executor.run_script( targets, script, [:leftovers] ) do |event| outputter.print_event(event) end when 'task' pal.run_task([:object], targets, [:task_options], executor, inventory) 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) executor.file_upload(targets, src, dest) 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 end |
#file_stat(path) ⇒ Object
523 524 525 |
# File 'lib/bolt/cli.rb', line 523 def file_stat(path) File.stat(path) end |
#get_arg_input(value) ⇒ Object
331 332 333 334 335 336 337 338 339 340 |
# File 'lib/bolt/cli.rb', line 331 def get_arg_input(value) if value.start_with?('@') file = value.sub(/^@/, '') read_arg_file(file) elsif value == '-' STDIN.read else value end end |
#handle_parser_errors ⇒ Object
400 401 402 403 404 405 406 |
# File 'lib/bolt/cli.rb', line 400 def handle_parser_errors yield rescue OptionParser::MissingArgument => e raise Bolt::CLIError, "Option '#{e.args.first}' needs a parameter" rescue OptionParser::InvalidOption, OptionParser::AmbiguousOption => e raise Bolt::CLIError, "Unknown argument '#{e.args.first}'" end |
#outputter ⇒ Object
527 528 529 |
# File 'lib/bolt/cli.rb', line 527 def outputter @outputter ||= Bolt::Outputter.for_format(@config[:format]) end |
#parse ⇒ Object
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 |
# File 'lib/bolt/cli.rb', line 265 def parse if @argv.empty? [:help] = true end remaining = handle_parser_errors do parser.permute(@argv) end # Shortcut to handle help before other errors may be generated [:mode] = remaining.shift if [:mode] == 'help' [:help] = true # regenerate options parser with new mode [:mode] = remaining.shift @parser = create_option_parser() end if [:help] puts parser.help raise Bolt::CLIExit end @config.load_file([:configfile]) @config.update_from_cli() @config.validate Logging.logger[:root].level = @config[:log_level] || :notice # This section handles parsing non-flag options which are # mode specific rather then part of the config [:action] = remaining.shift [: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 else [:task_options] = Hash[.map { |a| a.split('=', 2) }] end [:leftovers] = remaining validate() # After validation, initialize inventory and targets. Errors here are better to catch early. [:targets] = inventory.get_targets([:nodes]) if [:nodes] rescue Bolt::Error => e warn e. raise e end |
#parse_params(params) ⇒ Object
324 325 326 327 328 329 |
# File 'lib/bolt/cli.rb', line 324 def parse_params(params) json = get_arg_input(params) JSON.parse(json) rescue JSON::ParserError => err raise Bolt::CLIError, "Unable to parse --params value as JSON: #{err}" end |
#read_arg_file(file) ⇒ Object
342 343 344 345 346 |
# File 'lib/bolt/cli.rb', line 342 def read_arg_file(file) File.read(file) rescue StandardError => err raise Bolt::CLIError, "Error attempting to read #{file}: #{err}" end |
#validate(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 |
# File 'lib/bolt/cli.rb', line 348 def validate() unless COMMANDS.include?([:mode]) raise Bolt::CLIError, "Expected subcommand '#{[:mode]}' to be one of " \ "#{COMMANDS.keys.join(', ')}" end if [:action].nil? raise Bolt::CLIError, "Expected an action of the form 'bolt #{[:mode]} <action>'" end actions = COMMANDS[[:mode]] unless actions.include?([:action]) raise Bolt::CLIError, "Expected action '#{[:action]}' to be one of " \ "#{actions.join(', ')}" end if [:mode] != 'file' && [:mode] != 'script' && ![:leftovers].empty? raise Bolt::CLIError, "Unknown argument(s) #{[:leftovers].join(', ')}" end if %w[task plan].include?([:mode]) && [:action] == 'run' if [:object].nil? raise Bolt::CLIError, "Must specify a #{[:mode]} 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 #{[:mode]} '#{[:object]}'" end end if [:nodes].empty? && [:mode] != 'plan' && [:action] != 'show' raise Bolt::CLIError, "Option '--nodes' must be specified" end if %w[task plan].include?([:mode]) && @config[:modulepath].nil? raise Bolt::CLIError, "Option '--modulepath' must be specified when using" \ " a task or plan" end if [:noop] && ([:mode] != 'task' || [:action] != 'run') raise Bolt::CLIError, "Option '--noop' may only be specified when running a task" end end |
#validate_file(type, path) ⇒ Object
507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 |
# File 'lib/bolt/cli.rb', line 507 def validate_file(type, path) if path.nil? raise Bolt::CLIError, "A #{type} must be specified" end stat = file_stat(path) if !stat.readable? raise Bolt::CLIError, "The #{type} '#{path}' is unreadable" elsif !stat.file? raise Bolt::CLIError, "The #{type} '#{path}' is not a file" end rescue Errno::ENOENT raise Bolt::CLIError, "The #{type} '#{path}' does not exist" end |