Class: Chef::Knife

Inherits:
Object show all
Extended by:
Mixin::ConvertToClassName, Forwardable
Includes:
Mixlib::CLI
Defined in:
lib/chef/knife.rb,
lib/chef/knife/ssh.rb,
lib/chef/knife/help.rb,
lib/chef/knife/search.rb,
lib/chef/knife/status.rb,
lib/chef/knife/core/ui.rb,
lib/chef/knife/tag_list.rb,
lib/chef/knife/bootstrap.rb,
lib/chef/knife/configure.rb,
lib/chef/knife/node_edit.rb,
lib/chef/knife/node_list.rb,
lib/chef/knife/node_show.rb,
lib/chef/knife/role_edit.rb,
lib/chef/knife/role_list.rb,
lib/chef/knife/role_show.rb,
lib/chef/knife/tag_create.rb,
lib/chef/knife/tag_delete.rb,
lib/chef/knife/client_edit.rb,
lib/chef/knife/client_list.rb,
lib/chef/knife/client_show.rb,
lib/chef/knife/node_create.rb,
lib/chef/knife/node_delete.rb,
lib/chef/knife/role_create.rb,
lib/chef/knife/role_delete.rb,
lib/chef/knife/client_create.rb,
lib/chef/knife/client_delete.rb,
lib/chef/knife/cookbook_list.rb,
lib/chef/knife/cookbook_show.rb,
lib/chef/knife/cookbook_test.rb,
lib/chef/knife/data_bag_edit.rb,
lib/chef/knife/data_bag_list.rb,
lib/chef/knife/data_bag_show.rb,
lib/chef/knife/index_rebuild.rb,
lib/chef/knife/node_from_file.rb,
lib/chef/knife/role_from_file.rb,
lib/chef/knife/cookbook_create.rb,
lib/chef/knife/cookbook_delete.rb,
lib/chef/knife/cookbook_upload.rb,
lib/chef/knife/data_bag_create.rb,
lib/chef/knife/data_bag_delete.rb,
lib/chef/knife/configure_client.rb,
lib/chef/knife/core/node_editor.rb,
lib/chef/knife/environment_edit.rb,
lib/chef/knife/environment_list.rb,
lib/chef/knife/environment_show.rb,
lib/chef/knife/node_bulk_delete.rb,
lib/chef/knife/role_bulk_delete.rb,
lib/chef/knife/client_reregister.rb,
lib/chef/knife/cookbook_download.rb,
lib/chef/knife/cookbook_metadata.rb,
lib/chef/knife/node_run_list_add.rb,
lib/chef/knife/client_bulk_delete.rb,
lib/chef/knife/cookbook_site_list.rb,
lib/chef/knife/cookbook_site_show.rb,
lib/chef/knife/core/object_loader.rb,
lib/chef/knife/data_bag_from_file.rb,
lib/chef/knife/environment_create.rb,
lib/chef/knife/environment_delete.rb,
lib/chef/knife/cookbook_site_share.rb,
lib/chef/knife/core/node_presenter.rb,
lib/chef/knife/core/text_formatter.rb,
lib/chef/knife/cookbook_bulk_delete.rb,
lib/chef/knife/cookbook_site_search.rb,
lib/chef/knife/node_run_list_remove.rb,
lib/chef/knife/cookbook_site_install.rb,
lib/chef/knife/cookbook_site_unshare.rb,
lib/chef/knife/environment_from_file.rb,
lib/chef/knife/cookbook_site_download.rb,
lib/chef/knife/core/bootstrap_context.rb,
lib/chef/knife/core/cookbook_scm_repo.rb,
lib/chef/knife/core/generic_presenter.rb,
lib/chef/knife/core/subcommand_loader.rb,
lib/chef/knife/cookbook_metadata_from_file.rb

Defined Under Namespace

Modules: Core Classes: Bootstrap, ClientBulkDelete, ClientCreate, ClientDelete, ClientEdit, ClientList, ClientReregister, ClientShow, Configure, ConfigureClient, CookbookBulkDelete, CookbookCreate, CookbookDelete, CookbookDownload, CookbookList, CookbookMetadata, CookbookMetadataFromFile, CookbookSCMRepo, CookbookShow, CookbookSiteDownload, CookbookSiteInstall, CookbookSiteList, CookbookSiteSearch, CookbookSiteShare, CookbookSiteShow, CookbookSiteUnshare, CookbookSiteVendor, CookbookTest, CookbookUpload, DataBagCreate, DataBagDelete, DataBagEdit, DataBagFromFile, DataBagList, DataBagShow, EnvironmentCreate, EnvironmentDelete, EnvironmentEdit, EnvironmentFromFile, EnvironmentList, EnvironmentShow, Exec, Help, IndexRebuild, NodeBulkDelete, NodeCreate, NodeDelete, NodeEdit, NodeEditor, NodeFromFile, NodeList, NodeRunListAdd, NodeRunListRemove, NodeShow, RecipeList, RoleBulkDelete, RoleCreate, RoleDelete, RoleEdit, RoleFromFile, RoleList, RoleShow, Search, Ssh, Status, SubcommandLoader, TagCreate, TagDelete, TagList, UI

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Methods included from Mixin::ConvertToClassName

convert_to_class_name, convert_to_snake_case, filename_to_qualified_string, snake_case_basename

Constructor Details

#initialize(argv = []) ⇒ Knife

Create a new instance of the current class configured for the given arguments and options



259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
# File 'lib/chef/knife.rb', line 259

def initialize(argv=[])
  super() # having to call super in initialize is the most annoying anti-pattern :(
  @ui = Chef::Knife::UI.new(STDOUT, STDERR, STDIN, config)

  command_name_words = self.class.snake_case_name.split('_')

  # Mixlib::CLI ignores the embedded name_args
  @name_args = parse_options(argv)
  @name_args.delete(command_name_words.join('-'))
  @name_args.reject! { |name_arg| command_name_words.delete(name_arg) }

  # knife node run_list add requires that we have extra logic to handle
  # the case that command name words could be joined by an underscore :/
  command_name_words = command_name_words.join('_')
  @name_args.reject! { |name_arg| command_name_words == name_arg }

  if config[:help]
    msg opt_parser
    exit 1
  end
end

Instance Attribute Details

#name_argsObject

Returns the value of attribute name_args



55
56
57
# File 'lib/chef/knife.rb', line 55

def name_args
  @name_args
end

#uiObject

Returns the value of attribute ui



56
57
58
# File 'lib/chef/knife.rb', line 56

def ui
  @ui
end

Class Method Details

.category(new_category) ⇒ Object

Explicitly set the category for the current command to new_category The category is normally determined from the first word of the command name, but some commands make more sense using two or more words

Arguments

new_category:

A String to set the category to (see examples)

Examples:

Data bag commands would be in the 'data' category by default. To put them in the 'data bag' category:

category('data bag')


86
87
88
# File 'lib/chef/knife.rb', line 86

def self.category(new_category)
  @category = new_category
end

.common_nameObject



98
99
100
# File 'lib/chef/knife.rb', line 98

def self.common_name
  snake_case_name.split('_').join(' ')
end

.deps(&block) ⇒ Object



197
198
199
# File 'lib/chef/knife.rb', line 197

def self.deps(&block)
  @dependency_loader = block
end

.guess_category(args) ⇒ Object



169
170
171
172
173
174
175
176
177
178
179
# File 'lib/chef/knife.rb', line 169

def self.guess_category(args)
  category_words = args.select {|arg| arg =~ /^(([[:alnum:]])[[:alnum:]\_\-]+)$/ }
  category_words.map! {|w| w.split('-')}.flatten!
  matching_category = nil
  while (!matching_category) && (!category_words.empty?)
    candidate_category = category_words.join(' ')
    matching_category = candidate_category if subcommands_by_category.key?(candidate_category)
    matching_category || category_words.pop
  end
  matching_category
end

.inherited(subclass) ⇒ Object



71
72
73
74
75
# File 'lib/chef/knife.rb', line 71

def self.inherited(subclass)
  unless subclass.unnamed?
    subcommands[subclass.snake_case_name] = subclass
  end
end

.list_commands(preferred_category = nil) ⇒ Object

Print the list of subcommands knife knows about. If preferred_category is given, only subcommands in that category are shown



131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
# File 'lib/chef/knife.rb', line 131

def self.list_commands(preferred_category=nil)
  load_commands

  category_desc = preferred_category ? preferred_category + " " : ''
  msg "Available #{category_desc}subcommands: (for details, knife SUB-COMMAND --help)\n\n"

  if preferred_category && subcommands_by_category.key?(preferred_category)
    commands_to_show = {preferred_category => subcommands_by_category[preferred_category]}
  else
    commands_to_show = subcommands_by_category
  end

  commands_to_show.sort.each do |category, commands|
    next if category =~ /deprecated/i
    msg "** #{category.upcase} COMMANDS **"
    commands.each do |command|
      msg subcommands[command].banner if subcommands[command]
    end
    msg
  end
end

.load_commandsObject



111
112
113
# File 'lib/chef/knife.rb', line 111

def self.load_commands
  @commands_loaded ||= subcommand_loader.load_commands
end

.load_depsObject



201
202
203
# File 'lib/chef/knife.rb', line 201

def self.load_deps
  @dependency_loader && @dependency_loader.call
end

.msg(msg = "") ⇒ Object



62
63
64
# File 'lib/chef/knife.rb', line 62

def self.msg(msg="")
  ui.msg(msg)
end

.reset_subcommands!Object



66
67
68
69
# File 'lib/chef/knife.rb', line 66

def self.reset_subcommands!
  @@subcommands = {}
  @subcommands_by_category = nil
end

.run(args, options = {}) ⇒ Object

Run knife for the given args (ARGV), adding options to the list of CLI options that the subcommand knows how to handle.

Arguments

args:

usually ARGV

options:

A Mixlib::CLI option parser hash. These options are how

subcommands know about global knife CLI options



159
160
161
162
163
164
165
166
167
# File 'lib/chef/knife.rb', line 159

def self.run(args, options={})
  load_commands
  subcommand_class = subcommand_class_from(args)
  subcommand_class.options = options.merge!(subcommand_class.options)
  subcommand_class.load_deps unless want_help?(args)
  instance = subcommand_class.new(args)
  instance.configure_chef
  instance.run_with_pretty_exceptions
end

.snake_case_nameObject



94
95
96
# File 'lib/chef/knife.rb', line 94

def self.snake_case_name
  convert_to_snake_case(name.split('::').last) unless unnamed?
end

.subcommand_categoryObject



90
91
92
# File 'lib/chef/knife.rb', line 90

def self.subcommand_category
  @category || snake_case_name.split('_').first unless unnamed?
end

.subcommand_class_from(args) ⇒ Object



181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
# File 'lib/chef/knife.rb', line 181

def self.subcommand_class_from(args)
  command_words = args.select {|arg| arg =~ /^(([[:alnum:]])[[:alnum:]\_\-]+)$/ }

  subcommand_class = nil

  while ( !subcommand_class ) && ( !command_words.empty? )
    snake_case_class_name = command_words.join("_")
    unless subcommand_class = subcommands[snake_case_class_name]
      command_words.pop
    end
  end
  # see if we got the command as e.g., knife node-list
  subcommand_class ||= subcommands[args.first.gsub('-', '_')]
  subcommand_class || subcommand_not_found!(args)
end

.subcommand_loaderObject



107
108
109
# File 'lib/chef/knife.rb', line 107

def self.subcommand_loader
  @subcommand_loader ||= Knife::SubcommandLoader.new(chef_config_dir)
end

.subcommandsObject



115
116
117
# File 'lib/chef/knife.rb', line 115

def self.subcommands
  @@subcommands ||= {}
end

.subcommands_by_categoryObject



119
120
121
122
123
124
125
126
127
# File 'lib/chef/knife.rb', line 119

def self.subcommands_by_category
  unless @subcommands_by_category
    @subcommands_by_category = Hash.new { |hash, key| hash[key] = [] }
    subcommands.each do |snake_cased, klass|
      @subcommands_by_category[klass.subcommand_category] << snake_cased
    end
  end
  @subcommands_by_category
end

.uiObject



58
59
60
# File 'lib/chef/knife.rb', line 58

def self.ui
  @ui ||= Chef::Knife::UI.new(STDOUT, STDERR, STDIN, {})
end

.unnamed?Boolean

Does this class have a name? (Classes created via Class.new don't)



103
104
105
# File 'lib/chef/knife.rb', line 103

def self.unnamed?
  name.nil? || name.empty?
end

Instance Method Details

#api_keyObject



454
455
456
# File 'lib/chef/knife.rb', line 454

def api_key
  Chef::Config[:client_key]
end

#configure_chefObject



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/chef/knife.rb', line 289

def configure_chef
  unless config[:config_file]
    if self.class.chef_config_dir
      candidate_config = File.expand_path('knife.rb',self.class.chef_config_dir)
      config[:config_file] = candidate_config if File.exist?(candidate_config)
    end
    # If we haven't set a config yet and $HOME is set, and the home
    # knife.rb exists, use it:
    if (!config[:config_file]) && ENV['HOME'] && File.exist?(File.join(ENV['HOME'], '.chef', 'knife.rb'))
      config[:config_file] = File.join(ENV['HOME'], '.chef', 'knife.rb')
    end
  end

  # Don't try to load a knife.rb if it doesn't exist.
  if config[:config_file]
    read_config_file(config[:config_file])
  else
    # ...but do log a message if no config was found.
    Chef::Config[:color] = config[:color] && !config[:no_color]
    ui.warn("No knife configuration file found")
  end

  Chef::Config[:color] = config[:color] && !config[:no_color]

  case config[:verbosity]
  when 0
    Chef::Config[:log_level] = :error
  when 1
    Chef::Config[:log_level] = :info
  else
    Chef::Config[:log_level] = :debug
  end

  Chef::Config[:node_name]         = config[:node_name]       if config[:node_name]
  Chef::Config[:client_key]        = config[:client_key]      if config[:client_key]
  Chef::Config[:chef_server_url]   = config[:chef_server_url] if config[:chef_server_url]
  Chef::Config[:environment]       = config[:environment]     if config[:environment]

  # Expand a relative path from the config directory. Config from command
  # line should already be expanded, and absolute paths will be unchanged.
  if Chef::Config[:client_key] && config[:config_file]
    Chef::Config[:client_key] = File.expand_path(Chef::Config[:client_key], File.dirname(config[:config_file]))
  end

  Mixlib::Log::Formatter.show_time = false
  Chef::Log.init(Chef::Config[:log_location])
  Chef::Log.level(Chef::Config[:log_level] || :error)

  Chef::Log.debug("Using configuration from #{config[:config_file]}")

  if Chef::Config[:node_name].nil?
    #raise ArgumentError, "No user specified, pass via -u or specifiy 'node_name' in #{config[:config_file] ? config[:config_file] : "~/.chef/knife.rb"}"
  end
end

#create_object(object, pretty_name = nil, &block) ⇒ Object



468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
# File 'lib/chef/knife.rb', line 468

def create_object(object, pretty_name=nil, &block)
  output = edit_data(object)

  if Kernel.block_given?
    output = block.call(output)
  else
    output.save
  end

  pretty_name ||= output

  self.msg("Created #{pretty_name}")

  output(output) if config[:print_after]
end

#delete_object(klass, name, delete_name = nil, &block) ⇒ Object



484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
# File 'lib/chef/knife.rb', line 484

def delete_object(klass, name, delete_name=nil, &block)
  confirm("Do you really want to delete #{name}")

  if Kernel.block_given?
    object = block.call
  else
    object = klass.load(name)
    object.destroy
  end

  output(format_for_display(object)) if config[:print_after]

  obj_name = delete_name ? "#{delete_name}[#{name}]" : object
  self.msg("Deleted #{obj_name}")
end

#format_rest_error(response) ⇒ Object

Parses JSON from the error response sent by Chef Server and returns the error message – TODO: this code belongs in Chef::REST



462
463
464
465
466
# File 'lib/chef/knife.rb', line 462

def format_rest_error(response)
  Array(Chef::JSONCompat.from_json(response.body)["error"]).join('; ')
rescue Exception
  response.body
end

#highlight_config_error(file, line) ⇒ Object



367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
# File 'lib/chef/knife.rb', line 367

def highlight_config_error(file, line)
  config_file_lines = []
  IO.readlines(file).each_with_index {|l, i| config_file_lines << "#{(i + 1).to_s.rjust(3)}: #{l.chomp}"}
  if line == 1
    lines = config_file_lines[0..3]
    lines[0] = ui.color(lines[0], :red)
  else
    lines = config_file_lines[Range.new(line - 2, line)]
    lines[1] = ui.color(lines[1], :red)
  end
  ui.msg ""
  ui.msg ui.color("     # #{file}", :white)
  lines.each {|l| ui.msg(l)}
  ui.msg ""
end

#humanize_exception(e) ⇒ Object



398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
# File 'lib/chef/knife.rb', line 398

def humanize_exception(e)
  case e
  when SystemExit
    raise # make sure exit passes through.
  when Net::HTTPServerException, Net::HTTPFatalError
    humanize_http_exception(e)
  when Errno::ECONNREFUSED, Timeout::Error, Errno::ETIMEDOUT, SocketError
    ui.error "Network Error: #{e.message}"
    ui.info "Check your knife configuration and network settings"
  when NameError, NoMethodError
    ui.error "knife encountered an unexpected error"
    ui.info  "This may be a bug in the '#{self.class.common_name}' knife command or plugin"
    ui.info  "Please collect the output of this command with the `-VV` option before filing a bug report."
    ui.info  "Exception: #{e.class.name}: #{e.message}"
  when Chef::Exceptions::PrivateKeyMissing
    ui.error "Your private key could not be loaded from #{api_key}"
    ui.info  "Check your configuration file and ensure that your private key is readable"
  else
    ui.error "#{e.class.name}: #{e.message}"
  end
end

#humanize_http_exception(e) ⇒ Object



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
# File 'lib/chef/knife.rb', line 420

def humanize_http_exception(e)
  response = e.response
  case response
  when Net::HTTPUnauthorized
    ui.error "Failed to authenticate to #{server_url} as #{username} with key #{api_key}"
    ui.info "Response:  #{format_rest_error(response)}"
  when Net::HTTPForbidden
    ui.error "You authenticated successfully to #{server_url} as #{username} but you are not authorized for this action"
    ui.info "Response:  #{format_rest_error(response)}"
  when Net::HTTPBadRequest
    ui.error "The data in your request was invalid"
    ui.info "Response: #{format_rest_error(response)}"
  when Net::HTTPNotFound
    ui.error "The object you are looking for could not be found"
    ui.info "Response: #{format_rest_error(response)}"
  when Net::HTTPInternalServerError
    ui.error "internal server error"
    ui.info "Response: #{format_rest_error(response)}"
  when Net::HTTPBadGateway
    ui.error "bad gateway"
    ui.info "Response: #{format_rest_error(response)}"
  when Net::HTTPServiceUnavailable
    ui.error "Service temporarily unavailable"
    ui.info "Response: #{format_rest_error(response)}"
  else
    ui.error response.message
    ui.info "Response: #{format_rest_error(response)}"
  end
end

#noauth_restObject



507
508
509
510
511
512
# File 'lib/chef/knife.rb', line 507

def noauth_rest
  @rest ||= begin
    require 'chef/rest'
    Chef::REST.new(Chef::Config[:chef_server_url], false, false)
  end
end

#parse_options(args) ⇒ Object



281
282
283
284
285
286
287
# File 'lib/chef/knife.rb', line 281

def parse_options(args)
  super
rescue OptionParser::InvalidOption => e
  puts "Error: " + e.to_s
  show_usage
  exit(1)
end

#read_config_file(file) ⇒ Object



344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
# File 'lib/chef/knife.rb', line 344

def read_config_file(file)
  Chef::Config.from_file(file)
rescue SyntaxError => e
  ui.error "You have invalid ruby syntax in your config file #{file}"
  ui.info(ui.color(e.message, :red))
  if file_line = e.message[/#{Regexp.escape(file)}:[\d]+/]
    line = file_line[/:([\d]+)$/, 1].to_i
    highlight_config_error(file, line)
  end
  exit 1
rescue Exception => e
  ui.error "You have an error in your config file #{file}"
  ui.info "#{e.class.name}: #{e.message}"
  filtered_trace = e.backtrace.grep(/#{Regexp.escape(file)}/)
  filtered_trace.each {|line| ui.msg("  " + ui.color(line, :red))}
  if !filtered_trace.empty?
    line_nr = filtered_trace.first[/#{Regexp.escape(file)}:([\d]+)/, 1]
    highlight_config_error(file, line_nr.to_i)
  end

  exit 1
end

#restObject



500
501
502
503
504
505
# File 'lib/chef/knife.rb', line 500

def rest
  @rest ||= begin
    require 'chef/rest'
    Chef::REST.new(Chef::Config[:chef_server_url])
  end
end

#run_with_pretty_exceptionsObject



387
388
389
390
391
392
393
394
395
396
# File 'lib/chef/knife.rb', line 387

def run_with_pretty_exceptions
  unless self.respond_to?(:run)
    ui.error "You need to add a #run method to your knife command before you can use it"
  end
  run
rescue Exception => e
  raise if config[:verbosity] == 2
  humanize_exception(e)
  exit 100
end

#server_urlObject



514
515
516
# File 'lib/chef/knife.rb', line 514

def server_url
  Chef::Config[:chef_server_url]
end

#show_usageObject



383
384
385
# File 'lib/chef/knife.rb', line 383

def show_usage
  stdout.puts("USAGE: " + self.opt_parser.to_s)
end

#usernameObject



450
451
452
# File 'lib/chef/knife.rb', line 450

def username
  Chef::Config[:node_name]
end