Class: Chef::Knife
- Inherits:
-
Object
show all
- Extended by:
- Mixin::ConvertToClassName
- Includes:
- Mixlib::CLI
- Defined in:
- lib/chef/knife.rb,
lib/chef/knife/ssh.rb,
lib/chef/knife/search.rb,
lib/chef/knife/status.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/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/ec2_server_list.rb,
lib/chef/knife/configure_client.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/ec2_instance_data.rb,
lib/chef/knife/ec2_server_create.rb,
lib/chef/knife/ec2_server_delete.rb,
lib/chef/knife/node_run_list_add.rb,
lib/chef/knife/windows_bootstrap.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/data_bag_from_file.rb,
lib/chef/knife/bluebox_images_list.rb,
lib/chef/knife/bluebox_server_list.rb,
lib/chef/knife/cookbook_site_share.rb,
lib/chef/knife/cookbook_bulk_delete.rb,
lib/chef/knife/cookbook_site_search.rb,
lib/chef/knife/cookbook_site_vendor.rb,
lib/chef/knife/node_run_list_remove.rb,
lib/chef/knife/bluebox_server_create.rb,
lib/chef/knife/bluebox_server_delete.rb,
lib/chef/knife/cookbook_site_unshare.rb,
lib/chef/knife/rackspace_server_list.rb,
lib/chef/knife/slicehost_images_list.rb,
lib/chef/knife/slicehost_server_list.rb,
lib/chef/knife/terremark_server_list.rb,
lib/chef/knife/cookbook_site_download.rb,
lib/chef/knife/rackspace_server_create.rb,
lib/chef/knife/rackspace_server_delete.rb,
lib/chef/knife/slicehost_server_create.rb,
lib/chef/knife/slicehost_server_delete.rb,
lib/chef/knife/terremark_server_create.rb,
lib/chef/knife/terremark_server_delete.rb,
lib/chef/knife/cookbook_metadata_from_file.rb
Direct Known Subclasses
BlueboxImagesList, BlueboxServerCreate, BlueboxServerDelete, BlueboxServerList, Bootstrap, ClientBulkDelete, ClientCreate, ClientDelete, ClientEdit, ClientList, ClientReregister, ClientShow, Configure, ConfigureClient, CookbookBulkDelete, CookbookCreate, CookbookDelete, CookbookDownload, CookbookList, CookbookMetadata, CookbookMetadataFromFile, CookbookShow, CookbookSiteDownload, CookbookSiteList, CookbookSiteSearch, CookbookSiteShare, CookbookSiteShow, CookbookSiteUnshare, CookbookSiteVendor, CookbookTest, CookbookUpload, DataBagCreate, DataBagDelete, DataBagEdit, DataBagFromFile, DataBagList, DataBagShow, Ec2InstanceData, Ec2ServerCreate, Ec2ServerDelete, Ec2ServerList, Exec, IndexRebuild, NodeBulkDelete, NodeCreate, NodeDelete, NodeEdit, NodeFromFile, NodeList, NodeRunListAdd, NodeRunListRemove, NodeShow, RackspaceServerCreate, RackspaceServerDelete, RackspaceServerList, RecipeList, RoleBulkDelete, RoleCreate, RoleDelete, RoleEdit, RoleFromFile, RoleList, RoleShow, Search, SlicehostImagesList, SlicehostServerCreate, SlicehostServerDelete, SlicehostServerList, Ssh, Status, TerremarkServerCreate, TerremarkServerDelete, TerremarkServerList
Defined Under Namespace
Classes: BlueboxImagesList, BlueboxServerCreate, BlueboxServerDelete, BlueboxServerList, Bootstrap, ClientBulkDelete, ClientCreate, ClientDelete, ClientEdit, ClientList, ClientReregister, ClientShow, Configure, ConfigureClient, CookbookBulkDelete, CookbookCreate, CookbookDelete, CookbookDownload, CookbookList, CookbookMetadata, CookbookMetadataFromFile, CookbookShow, CookbookSiteDownload, CookbookSiteList, CookbookSiteSearch, CookbookSiteShare, CookbookSiteShow, CookbookSiteUnshare, CookbookSiteVendor, CookbookTest, CookbookUpload, DataBagCreate, DataBagDelete, DataBagEdit, DataBagFromFile, DataBagList, DataBagShow, Ec2InstanceData, Ec2ServerCreate, Ec2ServerDelete, Ec2ServerList, Exec, IndexRebuild, NodeBulkDelete, NodeCreate, NodeDelete, NodeEdit, NodeFromFile, NodeList, NodeRunListAdd, NodeRunListRemove, NodeShow, RackspaceServerCreate, RackspaceServerDelete, RackspaceServerList, RecipeList, RoleBulkDelete, RoleCreate, RoleDelete, RoleEdit, RoleFromFile, RoleList, RoleShow, Search, SlicehostImagesList, SlicehostServerCreate, SlicehostServerDelete, SlicehostServerList, Ssh, Status, TerremarkServerCreate, TerremarkServerDelete, TerremarkServerList, WindowsBootstrap
Constant Summary
collapse
- DEFAULT_SUBCOMMAND_FILES =
The “require paths” of the core knife subcommands bundled with chef
Dir[File.expand_path(File.join(File.dirname(__FILE__), 'knife', '*.rb'))]
Instance Attribute Summary collapse
Class Method Summary
collapse
Instance Method Summary
collapse
-
#ask_question(question, opts = {}) ⇒ Object
-
#bulk_delete(klass, fancy_name, delete_name = nil, list = nil, regex = nil, &block) ⇒ Object
-
#configure_chef ⇒ Object
-
#confirm(question, append_instructions = true) ⇒ Object
-
#create_object(object, pretty_name = nil, &block) ⇒ Object
-
#delete_object(klass, name, delete_name = nil, &block) ⇒ Object
-
#edit_data(data, parse_output = true) ⇒ Object
-
#edit_object(klass, name) ⇒ Object
-
#file_exists_and_is_readable?(file) ⇒ Boolean
-
#format_for_display(item) ⇒ Object
-
#format_list_for_display(list) ⇒ Object
-
#initialize(argv = []) ⇒ Knife
constructor
Create a new instance of the current class configured for the given arguments and options.
-
#load_from_file(klass, from_file, bag = nil) ⇒ Object
-
#msg(message) ⇒ Object
-
#output(data) ⇒ Object
-
#parse_options(args) ⇒ Object
-
#pretty_print(data) ⇒ Object
-
#rest ⇒ Object
-
#show_usage ⇒ Object
-
#stdin ⇒ Object
-
#stdout ⇒ Object
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
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
|
# File 'lib/chef/knife.rb', line 190
def initialize(argv=[])
super()
command_name_words = self.class.snake_case_name.split('_')
@name_args = parse_options(argv)
@name_args.reject! { |name_arg| command_name_words.delete(name_arg) }
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_args ⇒ Object
Returns the value of attribute name_args.
35
36
37
|
# File 'lib/chef/knife.rb', line 35
def name_args
@name_args
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')
56
57
58
|
# File 'lib/chef/knife.rb', line 56
def self.category(new_category)
@category = new_category
end
|
.guess_category(args) ⇒ Object
130
131
132
133
134
135
136
137
138
139
|
# File 'lib/chef/knife.rb', line 130
def self.guess_category(args)
category_words = args.select {|arg| arg =~ /^([[:alnum:]]|_)+$/ }
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
41
42
43
44
45
|
# File 'lib/chef/knife.rb', line 41
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
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
|
# File 'lib/chef/knife.rb', line 95
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|
msg "** #{category.upcase} COMMANDS **"
commands.each do |command|
msg subcommands[command].banner if subcommands[command]
end
msg
end
end
|
.load_commands ⇒ Object
Load all the sub-commands
88
89
90
91
|
# File 'lib/chef/knife.rb', line 88
def self.load_commands
DEFAULT_SUBCOMMAND_FILES.each { |subcommand| require subcommand }
subcommands
end
|
.msg(msg = "") ⇒ Object
37
38
39
|
# File 'lib/chef/knife.rb', line 37
def self.msg(msg="")
puts msg
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
121
122
123
124
125
126
127
128
|
# File 'lib/chef/knife.rb', line 121
def self.run(args, options={})
load_commands
subcommand_class = subcommand_class_from(args)
subcommand_class.options.merge!(options)
instance = subcommand_class.new(args)
instance.configure_chef
instance.run
end
|
.snake_case_name ⇒ Object
64
65
66
|
# File 'lib/chef/knife.rb', line 64
def self.snake_case_name
convert_to_snake_case(name.split('::').last) unless unnamed?
end
|
.subcommand_category ⇒ Object
60
61
62
|
# File 'lib/chef/knife.rb', line 60
def self.subcommand_category
@category || snake_case_name.split('_').first unless unnamed?
end
|
.subcommand_class_from(args) ⇒ Object
141
142
143
144
145
146
147
148
149
150
151
152
|
# File 'lib/chef/knife.rb', line 141
def self.subcommand_class_from(args)
command_words = args.select {|arg| arg =~ /^([[: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
subcommand_class || subcommand_not_found!(args)
end
|
.subcommands ⇒ Object
73
74
75
|
# File 'lib/chef/knife.rb', line 73
def self.subcommands
@@subcommands ||= {}
end
|
.subcommands_by_category ⇒ Object
77
78
79
80
81
82
83
84
85
|
# File 'lib/chef/knife.rb', line 77
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
|
.unnamed? ⇒ Boolean
Does this class have a name? (Classes created via Class.new don’t)
69
70
71
|
# File 'lib/chef/knife.rb', line 69
def self.unnamed?
name.nil? || name.empty?
end
|
Instance Method Details
#ask_question(question, opts = {}) ⇒ Object
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
|
# File 'lib/chef/knife.rb', line 218
def ask_question(question, opts={})
question = question + "[#{opts[:default]}] " if opts[:default]
if opts[:default] and config[:defaults]
opts[:default]
else
stdout.print question
a = stdin.readline.strip
if opts[:default]
a.empty? ? opts[:default] : a
else
a
end
end
end
|
#bulk_delete(klass, fancy_name, delete_name = nil, list = nil, regex = nil, &block) ⇒ Object
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
|
# File 'lib/chef/knife.rb', line 476
def bulk_delete(klass, fancy_name, delete_name=nil, list=nil, regex=nil, &block)
object_list = list ? list : klass.list(true)
if regex
to_delete = Hash.new
object_list.each_key do |object|
next if regex && object !~ /#{regex}/
to_delete[object] = object_list[object]
end
else
to_delete = object_list
end
output(format_list_for_display(to_delete))
confirm("Do you really want to delete the above items")
to_delete.each do |name, object|
if Kernel.block_given?
block.call(name, object)
else
object.destroy
end
output(format_for_display(object)) if config[:print_after]
self.msg("Deleted #{fancy_name} #{name}")
end
end
|
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
|
# File 'lib/chef/knife.rb', line 240
def configure_chef
unless config[:config_file]
full_path = Dir.pwd.split(File::SEPARATOR)
(full_path.length - 1).downto(0) do |i|
config_file_to_check = File.join([ full_path[0..i], ".chef", "knife.rb" ].flatten)
if File.exists?(config_file_to_check)
config[:config_file] = config_file_to_check
break
end
end
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
if config[:config_file]
Chef::Config.from_file(config[:config_file])
else
self.msg("No knife configuration file found")
end
Chef::Config[:log_level] = config[:log_level] if config[:log_level]
Chef::Config[:log_location] = config[:log_location] if config[:log_location]
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::Log.init(Chef::Config[:log_location])
Chef::Log.level(Chef::Config[:log_level])
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
|
#confirm(question, append_instructions = true) ⇒ Object
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
|
# File 'lib/chef/knife.rb', line 354
def confirm(question, append_instructions=true)
return true if config[:yes]
stdout.print question
stdout.print "? (Y/N) " if append_instructions
answer = stdin.readline
answer.chomp!
case answer
when "Y", "y"
true
when "N", "n"
self.msg("You said no, so I'm done here.")
exit 3
else
self.msg("I have no idea what to do with #{answer}")
self.msg("Just say Y or N, please.")
confirm(question)
end
end
|
#create_object(object, pretty_name = nil, &block) ⇒ Object
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
|
# File 'lib/chef/knife.rb', line 444
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 (or updated) #{pretty_name}")
output(output) if config[:print_after]
end
|
#delete_object(klass, name, delete_name = nil, &block) ⇒ Object
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
|
# File 'lib/chef/knife.rb', line 460
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
|
#edit_data(data, parse_output = true) ⇒ Object
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
|
# File 'lib/chef/knife.rb', line 332
def edit_data(data, parse_output=true)
output = Chef::JSONCompat.to_json_pretty(data)
if (!config[:no_editor])
filename = "knife-edit-"
0.upto(20) { filename += rand(9).to_s }
filename << ".js"
filename = File.join(Dir.tmpdir, filename)
tf = File.open(filename, "w")
tf.sync = true
tf.puts output
tf.close
raise "Please set EDITOR environment variable" unless system("#{config[:editor]} #{tf.path}")
tf = File.open(filename, "r")
output = tf.gets(nil)
tf.close
File.unlink(filename)
end
parse_output ? Chef::JSONCompat.from_json(output) : output
end
|
#edit_object(klass, name) ⇒ Object
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
|
# File 'lib/chef/knife.rb', line 417
def edit_object(klass, name)
object = klass.load(name)
output = edit_data(object)
object_parsed_again = Chef::JSONCompat.from_json(Chef::JSONCompat.to_json(object), :create_additions => false)
output_parsed_again = Chef::JSONCompat.from_json(Chef::JSONCompat.to_json(output), :create_additions => false)
if object_parsed_again != output_parsed_again
output.save
self.msg("Saved #{output}")
else
self.msg("Object unchanged, not saving")
end
output(format_for_display(object)) if config[:print_after]
end
|
#file_exists_and_is_readable?(file) ⇒ Boolean
413
414
415
|
# File 'lib/chef/knife.rb', line 413
def file_exists_and_is_readable?(file)
File.exists?(file) && File.readable?(file)
end
|
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
|
# File 'lib/chef/knife.rb', line 308
def format_for_display(item)
data = item.kind_of?(Chef::DataBagItem) ? item.raw_data : item
if config[:attribute]
config[:attribute].split(".").each do |attr|
if data.respond_to?(:[])
data = data[attr]
elsif data.nil?
nil else data.respond_to?(attr.to_sym)
data = data.send(attr.to_sym)
end
end
{ config[:attribute] => data.kind_of?(Chef::Node::Attribute) ? data.to_hash : data }
elsif config[:run_list]
data = data.run_list.run_list
{ "run_list" => data }
elsif config[:id_only]
data.respond_to?(:name) ? data.name : data["id"]
else
data
end
end
|
304
305
306
|
# File 'lib/chef/knife.rb', line 304
def format_list_for_display(list)
config[:with_uri] ? list : list.keys.sort { |a,b| a <=> b }
end
|
#load_from_file(klass, from_file, bag = nil) ⇒ Object
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
|
# File 'lib/chef/knife.rb', line 378
def load_from_file(klass, from_file, bag=nil)
relative_path = ""
if klass == Chef::Role
relative_path = "roles"
elsif klass == Chef::Node
relative_path = "nodes"
elsif klass == Chef::DataBagItem
relative_path = "data_bags/#{bag}"
end
relative_file = File.expand_path(File.join(Dir.pwd, relative_path, from_file))
filename = nil
if file_exists_and_is_readable?(from_file)
filename = from_file
elsif file_exists_and_is_readable?(relative_file)
filename = relative_file
else
Chef::Log.fatal("Cannot find file #{from_file}")
exit 30
end
case from_file
when /\.(js|json)$/
Chef::JSONCompat.from_json(IO.read(filename))
when /\.rb$/
r = klass.new
r.from_file(filename)
r
else
Chef::Log.fatal("File must end in .js, .json, or .rb")
exit 30
end
end
|
#msg(message) ⇒ Object
504
505
506
|
# File 'lib/chef/knife.rb', line 504
def msg(message)
stdout.puts message
end
|
#output(data) ⇒ Object
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
|
# File 'lib/chef/knife.rb', line 284
def output(data)
case config[:format]
when "json", nil
stdout.puts Chef::JSONCompat.to_json_pretty(data)
when "yaml"
require 'yaml'
stdout.puts YAML::dump(data)
when "text"
if data.length == 1 and config[:attribute]
stdout.puts data.values[0]
else
PP.pp(data, stdout)
end
else
raise ArgumentError, "Unknown output format #{config[:format]}"
end
end
|
#parse_options(args) ⇒ Object
210
211
212
213
214
215
216
|
# File 'lib/chef/knife.rb', line 210
def parse_options(args)
super
rescue OptionParser::InvalidOption => e
puts "Error: " + e.to_s
show_usage
exit(1)
end
|
#pretty_print(data) ⇒ Object
280
281
282
|
# File 'lib/chef/knife.rb', line 280
def pretty_print(data)
puts data
end
|
#rest ⇒ Object
516
517
518
|
# File 'lib/chef/knife.rb', line 516
def rest
@rest ||= Chef::REST.new(Chef::Config[:chef_server_url])
end
|
#show_usage ⇒ Object
374
375
376
|
# File 'lib/chef/knife.rb', line 374
def show_usage
stdout.puts("USAGE: " + self.opt_parser.to_s)
end
|
#stdin ⇒ Object
512
513
514
|
# File 'lib/chef/knife.rb', line 512
def stdin
STDIN
end
|
#stdout ⇒ Object
508
509
510
|
# File 'lib/chef/knife.rb', line 508
def stdout
STDOUT
end
|