Class: Chef::Knife
- Inherits:
-
Object
show all
- Extended by:
- Mixin::ConvertToClassName, Forwardable
- Includes:
- ChefUtils::DSL::DefaultPaths, Mixlib::CLI
- Defined in:
- lib/chef/knife.rb,
lib/chef/knife/raw.rb,
lib/chef/knife/ssh.rb,
lib/chef/knife/deps.rb,
lib/chef/knife/diff.rb,
lib/chef/knife/edit.rb,
lib/chef/knife/list.rb,
lib/chef/knife/null.rb,
lib/chef/knife/show.rb,
lib/chef/knife/serve.rb,
lib/chef/knife/xargs.rb,
lib/chef/knife/delete.rb,
lib/chef/knife/rehash.rb,
lib/chef/knife/search.rb,
lib/chef/knife/status.rb,
lib/chef/knife/upload.rb,
lib/chef/knife/acl_add.rb,
lib/chef/knife/core/ui.rb,
lib/chef/knife/license.rb,
lib/chef/knife/version.rb,
lib/chef/knife/acl_base.rb,
lib/chef/knife/acl_show.rb,
lib/chef/knife/download.rb,
lib/chef/knife/key_edit.rb,
lib/chef/knife/key_list.rb,
lib/chef/knife/key_show.rb,
lib/chef/knife/org_edit.rb,
lib/chef/knife/org_list.rb,
lib/chef/knife/org_show.rb,
lib/chef/knife/tag_list.rb,
lib/chef/knife/bootstrap.rb,
lib/chef/knife/configure.rb,
lib/chef/knife/group_add.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/ssl_check.rb,
lib/chef/knife/ssl_fetch.rb,
lib/chef/knife/user_edit.rb,
lib/chef/knife/user_list.rb,
lib/chef/knife/user_show.rb,
lib/chef/knife/acl_remove.rb,
lib/chef/knife/config_get.rb,
lib/chef/knife/config_use.rb,
lib/chef/knife/group_list.rb,
lib/chef/knife/group_show.rb,
lib/chef/knife/key_create.rb,
lib/chef/knife/key_delete.rb,
lib/chef/knife/org_create.rb,
lib/chef/knife/org_delete.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/config_list.rb,
lib/chef/knife/config_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/user_create.rb,
lib/chef/knife/user_delete.rb,
lib/chef/knife/acl_bulk_add.rb,
lib/chef/knife/group_create.rb,
lib/chef/knife/group_remove.rb,
lib/chef/knife/org_user_add.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/data_bag_edit.rb,
lib/chef/knife/data_bag_list.rb,
lib/chef/knife/data_bag_show.rb,
lib/chef/knife/group_destroy.rb,
lib/chef/knife/key_edit_base.rb,
lib/chef/knife/key_list_base.rb,
lib/chef/knife/user_key_edit.rb,
lib/chef/knife/user_key_list.rb,
lib/chef/knife/user_key_show.rb,
lib/chef/knife/user_password.rb,
lib/chef/knife/node_from_file.rb,
lib/chef/knife/role_from_file.rb,
lib/chef/knife/acl_bulk_remove.rb,
lib/chef/knife/client_key_edit.rb,
lib/chef/knife/client_key_list.rb,
lib/chef/knife/client_key_show.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/key_create_base.rb,
lib/chef/knife/node_policy_set.rb,
lib/chef/knife/org_user_remove.rb,
lib/chef/knife/user_dissociate.rb,
lib/chef/knife/user_invite_add.rb,
lib/chef/knife/user_key_create.rb,
lib/chef/knife/user_key_delete.rb,
lib/chef/knife/user_reregister.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/supermarket_list.rb,
lib/chef/knife/supermarket_show.rb,
lib/chef/knife/user_invite_list.rb,
lib/chef/knife/client_key_create.rb,
lib/chef/knife/client_key_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/node_run_list_set.rb,
lib/chef/knife/role_run_list_add.rb,
lib/chef/knife/role_run_list_set.rb,
lib/chef/knife/supermarket_share.rb,
lib/chef/knife/client_bulk_delete.rb,
lib/chef/knife/config_get_profile.rb,
lib/chef/knife/config_use_profile.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/supermarket_search.rb,
lib/chef/knife/core/node_presenter.rb,
lib/chef/knife/core/text_formatter.rb,
lib/chef/knife/environment_compare.rb,
lib/chef/knife/role_run_list_clear.rb,
lib/chef/knife/supermarket_install.rb,
lib/chef/knife/supermarket_unshare.rb,
lib/chef/knife/user_invite_rescind.rb,
lib/chef/knife/config_list_profiles.rb,
lib/chef/knife/cookbook_bulk_delete.rb,
lib/chef/knife/core/gem_glob_loader.rb,
lib/chef/knife/node_environment_set.rb,
lib/chef/knife/node_run_list_remove.rb,
lib/chef/knife/role_run_list_remove.rb,
lib/chef/knife/supermarket_download.rb,
lib/chef/knife/core/status_presenter.rb,
lib/chef/knife/environment_from_file.rb,
lib/chef/knife/role_env_run_list_add.rb,
lib/chef/knife/role_env_run_list_set.rb,
lib/chef/knife/role_run_list_replace.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/core/formatting_options.rb,
lib/chef/knife/data_bag_secret_options.rb,
lib/chef/knife/role_env_run_list_clear.rb,
lib/chef/knife/bootstrap/client_builder.rb,
lib/chef/knife/role_env_run_list_remove.rb,
lib/chef/knife/bootstrap/train_connector.rb,
lib/chef/knife/role_env_run_list_replace.rb,
lib/chef/knife/core/hashed_command_loader.rb,
lib/chef/knife/cookbook_metadata_from_file.rb,
lib/chef/knife/bootstrap/chef_vault_handler.rb,
lib/chef/knife/core/windows_bootstrap_context.rb,
lib/chef/knife/core/cookbook_site_streaming_uploader.rb
Direct Known Subclasses
ChefFS::Knife, AclAdd, AclBulkAdd, AclBulkRemove, AclRemove, AclShow, Bootstrap, ClientBulkDelete, ClientCreate, ClientDelete, ClientEdit, ClientKeyCreate, ClientKeyDelete, ClientKeyEdit, ClientKeyList, ClientKeyShow, ClientList, ClientReregister, ClientShow, ConfigList, ConfigShow, ConfigUse, Configure, ConfigureClient, CookbookBulkDelete, CookbookDelete, CookbookDownload, CookbookList, CookbookMetadata, CookbookMetadataFromFile, CookbookShow, CookbookUpload, DataBagCreate, DataBagDelete, DataBagEdit, DataBagFromFile, DataBagList, DataBagShow, EnvironmentCompare, EnvironmentCreate, EnvironmentDelete, EnvironmentEdit, EnvironmentFromFile, EnvironmentList, EnvironmentShow, Exec, GroupAdd, GroupCreate, GroupDestroy, GroupList, GroupRemove, GroupShow, License, NodeBulkDelete, NodeCreate, NodeDelete, NodeEdit, NodeEnvironmentSet, NodeFromFile, NodeList, NodePolicySet, NodeRunListAdd, NodeRunListRemove, NodeRunListSet, NodeShow, Null, OrgCreate, OrgDelete, OrgEdit, OrgList, OrgShow, OrgUserAdd, OrgUserRemove, Raw, RecipeList, Rehash, RoleBulkDelete, RoleCreate, RoleDelete, RoleEdit, RoleEnvRunListAdd, RoleEnvRunListClear, RoleEnvRunListRemove, RoleEnvRunListReplace, RoleEnvRunListSet, RoleFromFile, RoleList, RoleRunListAdd, RoleRunListClear, RoleRunListRemove, RoleRunListReplace, RoleRunListSet, RoleShow, Search, Serve, Ssh, SslCheck, SslFetch, Status, SupermarketDownload, SupermarketInstall, SupermarketList, SupermarketSearch, SupermarketShare, SupermarketShow, SupermarketUnshare, TagCreate, TagDelete, TagList, UserCreate, UserDelete, UserDissociate, UserEdit, UserInviteAdd, UserInviteList, UserInviteRescind, UserKeyCreate, UserKeyDelete, UserKeyEdit, UserKeyList, UserKeyShow, UserList, UserPassword, UserReregister, UserShow, YamlConvert
Defined Under Namespace
Modules: AclBase, Core, DataBagSecretOptions, KeyCreateBase, KeyEditBase, KeyListBase
Classes: AclAdd, AclBulkAdd, AclBulkRemove, AclRemove, AclShow, Bootstrap, ClientBulkDelete, ClientCreate, ClientDelete, ClientEdit, ClientKeyCreate, ClientKeyDelete, ClientKeyEdit, ClientKeyList, ClientKeyShow, ClientList, ClientReregister, ClientShow, ConfigGet, ConfigGetProfile, ConfigList, ConfigListProfiles, ConfigShow, ConfigUse, ConfigUseProfile, Configure, ConfigureClient, CookbookBulkDelete, CookbookDelete, CookbookDownload, CookbookList, CookbookMetadata, CookbookMetadataFromFile, CookbookSCMRepo, CookbookShow, CookbookUpload, DataBagCreate, DataBagDelete, DataBagEdit, DataBagFromFile, DataBagList, DataBagShow, Delete, Deps, Diff, Download, Edit, EnvironmentCompare, EnvironmentCreate, EnvironmentDelete, EnvironmentEdit, EnvironmentFromFile, EnvironmentList, EnvironmentShow, Exec, GroupAdd, GroupCreate, GroupDestroy, GroupList, GroupRemove, GroupShow, KeyCreate, KeyDelete, KeyEdit, KeyList, KeyShow, License, List, NodeBulkDelete, NodeCreate, NodeDelete, NodeEdit, NodeEditor, NodeEnvironmentSet, NodeFromFile, NodeList, NodePolicySet, NodeRunListAdd, NodeRunListRemove, NodeRunListSet, NodeShow, Null, OrgCreate, OrgDelete, OrgEdit, OrgList, OrgShow, OrgUserAdd, OrgUserRemove, Raw, RecipeList, Rehash, RoleBulkDelete, RoleCreate, RoleDelete, RoleEdit, RoleEnvRunListAdd, RoleEnvRunListClear, RoleEnvRunListRemove, RoleEnvRunListReplace, RoleEnvRunListSet, RoleFromFile, RoleList, RoleRunListAdd, RoleRunListClear, RoleRunListRemove, RoleRunListReplace, RoleRunListSet, RoleShow, Search, Serve, Show, Ssh, SslCheck, SslFetch, Status, SubcommandLoader, SupermarketDownload, SupermarketInstall, SupermarketList, SupermarketSearch, SupermarketShare, SupermarketShow, SupermarketUnshare, TagCreate, TagDelete, TagList, UI, Upload, UserCreate, UserDelete, UserDissociate, UserEdit, UserInviteAdd, UserInviteList, UserInviteRescind, UserKeyCreate, UserKeyDelete, UserKeyEdit, UserKeyList, UserKeyShow, UserList, UserPassword, UserReregister, UserShow, Xargs, YamlConvert
Constant Summary
collapse
- OPSCODE_HOSTED_CHEF_ACCESS_CONTROL =
knife acl subcommands are grouped in this category using this constant to verify.
%w{acl group user}.freeze
- CHEF_ORGANIZATION_MANAGEMENT =
knife opc subcommands are grouped in this category using this constant to verify.
%w{opc}.freeze
- OFFICIAL_PLUGINS =
%w{lpar openstack push rackspace vcenter}.freeze
- KNIFE_ROOT =
File.expand_path("../..", __dir__)
- VERSION =
"18.6.2".freeze
- @@chef_config_dir =
nil
Instance Attribute Summary collapse
Class Method Summary
collapse
Instance Method Summary
collapse
Constructor Details
#initialize(argv = []) ⇒ Knife
Create a new instance of the current class configured for the given arguments and options
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
|
# File 'lib/chef/knife.rb', line 308
def initialize(argv = [])
super() @ui = Chef::Knife::UI.new(STDOUT, STDERR, STDIN, config)
command_name_words = self.class.snake_case_name.split("_")
@name_args = parse_options(argv)
@name_args.delete(command_name_words.join("-"))
@name_args.reject! { |name_arg| command_name_words.delete(name_arg) }
command_name_joined = command_name_words.join("_")
@name_args.reject! { |name_arg| command_name_joined == name_arg }
command_name_joined = command_name_words.join("-")
@name_args.reject! { |name_arg| command_name_joined == name_arg }
if config[:help]
msg opt_parser
exit 1
end
@original_config = config.dup
Chef::Config[:verbosity] = config[:verbosity] if config[:verbosity]
end
|
Instance Attribute Details
#name_args ⇒ Object
Returns the value of attribute name_args.
69
70
71
|
# File 'lib/chef/knife.rb', line 69
def name_args
@name_args
end
|
#ui ⇒ Object
Returns the value of attribute ui.
70
71
72
|
# File 'lib/chef/knife.rb', line 70
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
126
127
128
|
# File 'lib/chef/knife.rb', line 126
def self.category(new_category)
@category = new_category
end
|
.chef_config_dir ⇒ Object
206
207
208
|
# File 'lib/chef/knife.rb', line 206
def self.chef_config_dir
@@chef_config_dir ||= config_loader.chef_config_dir
end
|
.common_name ⇒ Object
138
139
140
|
# File 'lib/chef/knife.rb', line 138
def self.common_name
snake_case_name.split("_").join(" ")
end
|
.config_loader ⇒ Object
189
190
191
|
# File 'lib/chef/knife.rb', line 189
def self.config_loader
@config_loader ||= WorkstationConfigLoader.new(nil, Chef::Log)
end
|
.dependency_loaders ⇒ Object
236
237
238
|
# File 'lib/chef/knife.rb', line 236
def self.dependency_loaders
@dependency_loaders ||= []
end
|
.deps(&block) ⇒ Object
240
241
242
|
# File 'lib/chef/knife.rb', line 240
def self.deps(&block)
dependency_loaders << block
end
|
.guess_category(args) ⇒ Object
155
156
157
|
# File 'lib/chef/knife.rb', line 155
def self.guess_category(args)
subcommand_loader.guess_category(args)
end
|
.inherited(subclass) ⇒ Object
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
|
# File 'lib/chef/knife.rb', line 101
def self.inherited(subclass)
super
unless subclass.unnamed?
subcommands[subclass.snake_case_name] = subclass
subcommand_files[subclass.snake_case_name] +=
if subclass.superclass.to_s == "Chef::ChefFS::Knife"
[path_from_caller(caller[1])]
else
[path_from_caller(caller[0])]
end
end
end
|
.list_commands(preferred_category = nil) ⇒ Object
251
252
253
254
255
256
257
258
259
260
261
262
263
264
|
# File 'lib/chef/knife.rb', line 251
def list_commands(preferred_category = nil)
category_desc = preferred_category ? preferred_category + " " : ""
msg "Available #{category_desc}subcommands: (for details, knife SUB-COMMAND --help)\n\n"
subcommand_loader.list_commands(preferred_category).sort.each do |category, commands|
next if /deprecated/i.match?(category)
msg "** #{category.upcase} COMMANDS **"
commands.sort.each do |command|
subcommand_loader.load_command(command)
msg subcommands[command].banner if subcommands[command]
end
msg
end
end
|
.load_commands ⇒ Object
151
152
153
|
# File 'lib/chef/knife.rb', line 151
def self.load_commands
@commands_loaded ||= subcommand_loader.load_commands
end
|
.load_config(explicit_config_file, profile) ⇒ Object
193
194
195
196
197
198
199
200
201
202
203
204
|
# File 'lib/chef/knife.rb', line 193
def self.load_config(explicit_config_file, profile)
config_loader.explicit_config_file = explicit_config_file
config_loader.profile = profile
config_loader.load
ui.warn("No knife configuration file found. See https://docs.chef.io/config_rb/ for details.") if config_loader.no_config_found?
config_loader
rescue Exceptions::ConfigurationError => e
ui.error(ui.color("CONFIGURATION ERROR:", :red) + e.message)
exit 1
end
|
.load_deps ⇒ Object
244
245
246
|
# File 'lib/chef/knife.rb', line 244
def self.load_deps
dependency_loaders.each(&:call)
end
|
.msg(msg = "") ⇒ Object
87
88
89
|
# File 'lib/chef/knife.rb', line 87
def self.msg(msg = "")
ui.msg(msg)
end
|
.reset_config_loader! ⇒ Object
91
92
93
94
|
# File 'lib/chef/knife.rb', line 91
def self.reset_config_loader!
@@chef_config_dir = nil
@config_loader = nil
end
|
.reset_subcommands! ⇒ Object
96
97
98
99
|
# File 'lib/chef/knife.rb', line 96
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.
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
|
# File 'lib/chef/knife.rb', line 217
def self.run(args, options = {})
if ENV["KNIFE_DEBUG"]
Chef::Log.init($stderr)
Chef::Log.level(:debug)
end
subcommand_class = subcommand_class_from(args)
subcommand_class.options = options.merge!(subcommand_class.options)
subcommand_class.load_deps
instance = subcommand_class.new(args)
instance.configure_chef
instance.run_with_pretty_exceptions
end
|
.snake_case_name ⇒ Object
134
135
136
|
# File 'lib/chef/knife.rb', line 134
def self.snake_case_name
convert_to_snake_case(name.split("::").last) unless unnamed?
end
|
.subcommand_category ⇒ Object
130
131
132
|
# File 'lib/chef/knife.rb', line 130
def self.subcommand_category
@category || snake_case_name.split("_").first unless unnamed?
end
|
.subcommand_class_from(args) ⇒ Object
159
160
161
162
163
164
165
166
|
# File 'lib/chef/knife.rb', line 159
def self.subcommand_class_from(args)
if args.size == 1 && args[0].strip.casecmp("rehash") == 0
@subcommand_loader = Chef::Knife::SubcommandLoader.gem_glob_loader(chef_config_dir)
end
subcommand_loader.command_class_from(args) || subcommand_not_found!(args)
end
|
.subcommand_files ⇒ Object
172
173
174
|
# File 'lib/chef/knife.rb', line 172
def self.subcommand_files
@@subcommand_files ||= Hash.new([])
end
|
.subcommand_loader ⇒ Object
.subcommands ⇒ Object
168
169
170
|
# File 'lib/chef/knife.rb', line 168
def self.subcommands
@@subcommands ||= {}
end
|
.subcommands_by_category ⇒ Object
176
177
178
179
180
181
182
183
184
|
# File 'lib/chef/knife.rb', line 176
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
|
.ui ⇒ Object
83
84
85
|
# File 'lib/chef/knife.rb', line 83
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)
143
144
145
|
# File 'lib/chef/knife.rb', line 143
def self.unnamed?
name.nil? || name.empty?
end
|
.use_separate_defaults? ⇒ Boolean
Configure mixlib-cli to always separate defaults from user-supplied CLI options
79
80
81
|
# File 'lib/chef/knife.rb', line 79
def self.use_separate_defaults?
true
end
|
Instance Method Details
#api_key ⇒ Object
586
587
588
|
# File 'lib/chef/knife.rb', line 586
def api_key
Chef::Config[:client_key]
end
|
#apply_computed_config ⇒ Object
Catch-all method that does any massaging needed for various config components, such as expanding file paths and converting verbosity level into log level.
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
|
# File 'lib/chef/knife.rb', line 414
def apply_computed_config
Chef::Config[:color] = config[:color]
Chef::Config[:log_level] = case Chef::Config[:verbosity]
when 0
:warn
when 1
:info
when 2
:debug
when nil
Chef::Config[:log_level] == :auto ? :warn : Chef::Config[:log_level]
else
:trace
end
Chef::Config[:log_level] = :trace if ENV["KNIFE_DEBUG"]
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]
Chef::Config.local_mode = config[:local_mode] if config.key?(:local_mode)
Chef::Config.listen = config[:listen] if config.key?(:listen)
if Chef::Config.local_mode && !Chef::Config.key?(:cookbook_path) && !Chef::Config.key?(:chef_repo_path)
Chef::Config.chef_repo_path = Chef::Config.find_chef_repo_path(Dir.pwd)
end
Chef::Config.chef_zero.host = config[:chef_zero_host] if config[:chef_zero_host]
Chef::Config.chef_zero.port = config[:chef_zero_port] if config[:chef_zero_port]
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)
end
|
#config_file_defaults ⇒ Object
This method is part of a private API.
You should avoid using this method if possible, as it may be removed or be changed in the future.
This is all set and default mixlib-config values. We only need the default values here (the set values are explicitly mixed in again later), but there is no mixlib-config API to get a Hash back with only the default values.
Assumption: since config_file_defaults is the lowest precedence it doesn’t matter that we include the set values here, but this is a hack and makes the name of the method a lie. FIXME: make the name not a lie by adding an API to mixlib-config.
360
361
362
|
# File 'lib/chef/knife.rb', line 360
def config_file_defaults
Chef::Config[:knife].save(true) end
|
#config_file_settings ⇒ Object
This method is part of a private API.
You should avoid using this method if possible, as it may be removed or be changed in the future.
This is only the user-set mixlib-config values. We do not include the defaults here so that the config defaults do not override the cli defaults.
369
370
371
|
# File 'lib/chef/knife.rb', line 369
def config_file_settings
Chef::Config[:knife].save(false) end
|
#config_source(key) ⇒ Symbol, NilClass
Determine the source of a given configuration key
one of:
- :cli - this was explicitly provided on the CLI
- :config - this came from Chef::Config[:knife] explicitly being set
- :cli_default - came from a declared CLI `option`'s `default` value.
- :config_default - this came from Chef::Config[:knife]'s defaults
- nil - if the key could not be found in any source.
This can happen when it is invalid, or has been
set directly into #config without then calling #merge_config
402
403
404
405
406
407
408
409
|
# File 'lib/chef/knife.rb', line 402
def config_source(key)
return :cli if @original_config.include? key
return :config if config_file_settings.key? key
return :cli_default if default_config.include? key
return :config_default if config_file_defaults.key? key
nil
end
|
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
|
# File 'lib/chef/knife.rb', line 460
def configure_chef
Chef::Config[:log_location] = STDERR
config_loader = self.class.load_config(config[:config_file], config[:profile])
config[:config_file] = config_loader.config_location
= config.delete(:config_option)
merge_configs
apply_computed_config
Chef::Log.info("Using configuration from #{config[:config_file]}") if config[:config_file]
begin
Chef::Config.()
rescue ChefConfig::UnparsableConfigOption => e
ui.error e.message
show_usage
exit(1)
end
Chef::Config.export_proxies
end
|
#create_object(object, pretty_name = nil, object_class: nil) ⇒ Object
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
|
# File 'lib/chef/knife.rb', line 601
def create_object(object, pretty_name = nil, object_class: nil)
output = if object_class
edit_data(object, object_class: object_class)
else
edit_hash(object)
end
if Kernel.block_given?
output = yield(output)
else
output.save
end
pretty_name ||= output
msg("Created #{pretty_name}")
output(output) if config[:print_after]
end
|
#delete_object(klass, name, delete_name = nil) ⇒ Object
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
|
# File 'lib/chef/knife.rb', line 622
def delete_object(klass, name, delete_name = nil)
confirm("Do you really want to delete #{name}")
if Kernel.block_given?
object = yield
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
msg("Deleted #{obj_name}")
end
|
Parses JSON from the error response sent by Chef Server and returns the error message – TODO: this code belongs in Chef::REST
594
595
596
597
598
|
# File 'lib/chef/knife.rb', line 594
def format_rest_error(response)
Array(Chef::JSONCompat.from_json(response.body)["error"]).join("; ")
rescue Exception
response.body
end
|
#humanize_exception(e) ⇒ Object
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
537
|
# File 'lib/chef/knife.rb', line 507
def humanize_exception(e)
case e
when SystemExit
raise when Net::HTTPClientException, Net::HTTPFatalError
humanize_http_exception(e)
when OpenSSL::SSL::SSLError
ui.error "Could not establish a secure connection to the server."
ui.info "Use `knife ssl check` to troubleshoot your SSL configuration."
ui.info "If your server uses a self-signed certificate, you can use"
ui.info "`knife ssl fetch` to make knife trust the server's certificates."
ui.info ""
ui.info "Original Exception: #{e.class.name}: #{e.message}"
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 `-VVV` 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"
when Chef::Exceptions::InvalidRedirect
ui.error "Invalid Redirect: #{e.message}"
ui.info "Change your server location in config.rb/knife.rb to the server's FQDN to avoid unwanted redirections."
else
ui.error "#{e.class.name}: #{e.message}"
end
end
|
#humanize_http_exception(e) ⇒ Object
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
|
# File 'lib/chef/knife.rb', line 539
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."
proxy_env_vars = ENV.to_hash.keys.map(&:downcase) & %w{http_proxy https_proxy ftp_proxy socks_proxy no_proxy}
unless proxy_env_vars.empty?
ui.error "There are proxy servers configured, your server url may need to be added to NO_PROXY."
end
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)}"
when Net::HTTPNotAcceptable
= Chef::JSONCompat.from_json(response["x-ops-server-api-version"])
client_api_version = ["request_version"]
min_server_version = ["min_version"]
max_server_version = ["max_version"]
ui.error "The API version that Knife is using is not supported by the server you sent this request to."
ui.info "The request that Knife sent was using API version #{client_api_version}."
ui.info "The server you sent the request to supports a min API version of #{min_server_version} and a max API version of #{max_server_version}."
ui.info "Please either update your #{ChefUtils::Dist::Infra::PRODUCT} or the server to be a compatible set."
else
ui.error response.message
ui.info "Response: #{format_rest_error(response)}"
end
end
|
#maybe_setup_fips ⇒ Object
663
664
665
666
667
668
|
# File 'lib/chef/knife.rb', line 663
def maybe_setup_fips
unless config[:fips].nil?
Chef::Config[:fips] = config[:fips]
end
Chef::Config.init_openssl
end
|
#merge_configs ⇒ Object
config is merged in this order (inverse of precedence)
config_file_defaults - Chef::Config[:knife] defaults from chef-config (XXX: this also includes the settings, but they get overwritten)
default_config - mixlib-cli defaults (accessor from mixlib-cli)
config_file_settings - Chef::Config[:knife] user settings from the client.rb file
config - mixlib-cli settings (accessor from mixlib-cli)
379
380
381
382
383
384
385
386
387
|
# File 'lib/chef/knife.rb', line 379
def merge_configs
@original_config = config.dup
config.replace(config_file_defaults.merge(default_config).merge(config_file_settings).merge(config))
end
|
#noauth_rest ⇒ Object
652
653
654
655
656
657
|
# File 'lib/chef/knife.rb', line 652
def noauth_rest
@rest ||= begin
require "chef/http/simple_json" unless defined?(Chef::HTTP::SimpleJSON)
Chef::HTTP::SimpleJSON.new(Chef::Config[:chef_server_url])
end
end
|
#parse_options(args) ⇒ Object
342
343
344
345
346
347
348
|
# File 'lib/chef/knife.rb', line 342
def parse_options(args)
super
rescue OptionParser::InvalidOption => e
puts "Error: " + e.to_s
show_usage
exit(1)
end
|
#rest ⇒ Object
648
649
650
|
# File 'lib/chef/knife.rb', line 648
def rest
@rest ||= Chef::ServerAPI.new(Chef::Config[:chef_server_url])
end
|
#root_rest ⇒ Object
670
671
672
673
674
675
|
# File 'lib/chef/knife.rb', line 670
def root_rest
@root_rest ||= begin
require "chef/server_api" unless defined? Chef::ServerAPI
Chef::ServerAPI.new(Chef::Config[:chef_server_root])
end
end
|
#run_with_pretty_exceptions(raise_exception = false) ⇒ Object
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
|
# File 'lib/chef/knife.rb', line 491
def run_with_pretty_exceptions(raise_exception = false)
unless respond_to?(:run)
ui.error "You need to add a #run method to your knife command before you can use it"
end
ENV["PATH"] = default_paths if Chef::Config[:enforce_default_paths] || Chef::Config[:enforce_path_sanity]
maybe_setup_fips
Chef::LocalMode.with_server_connectivity do
run
end
rescue Exception => e
raise if raise_exception || ( Chef::Config[:verbosity] && Chef::Config[:verbosity] >= 2 )
humanize_exception(e)
exit 100
end
|
#server_url ⇒ Object
659
660
661
|
# File 'lib/chef/knife.rb', line 659
def server_url
Chef::Config[:chef_server_url]
end
|
#show_usage ⇒ Object
487
488
489
|
# File 'lib/chef/knife.rb', line 487
def show_usage
stdout.puts("USAGE: " + opt_parser.to_s)
end
|
#test_mandatory_field(field, fieldname) ⇒ Object
helper method for testing if a field exists and returning the usage and proper error if not
640
641
642
643
644
645
646
|
# File 'lib/chef/knife.rb', line 640
def test_mandatory_field(field, fieldname)
if field.nil?
show_usage
ui.fatal("You must specify a #{fieldname}")
exit 1
end
end
|
#username ⇒ Object
582
583
584
|
# File 'lib/chef/knife.rb', line 582
def username
Chef::Config[:node_name]
end
|