chef-config 14.0.202 → 14.1.1

Sign up to get free protection for your applications and to get access to all the features.
@@ -1,20 +1,20 @@
1
- #
2
- # Copyright:: Copyright 2015-2016, Chef Software, Inc.
3
- # License:: Apache License, Version 2.0
4
- #
5
- # Licensed under the Apache License, Version 2.0 (the "License");
6
- # you may not use this file except in compliance with the License.
7
- # You may obtain a copy of the License at
8
- #
9
- # http://www.apache.org/licenses/LICENSE-2.0
10
- #
11
- # Unless required by applicable law or agreed to in writing, software
12
- # distributed under the License is distributed on an "AS IS" BASIS,
13
- # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
- # See the License for the specific language governing permissions and
15
- # limitations under the License.
16
- #
17
-
18
- module ChefConfig
19
-
20
- end
1
+ #
2
+ # Copyright:: Copyright 2015-2016, Chef Software, Inc.
3
+ # License:: Apache License, Version 2.0
4
+ #
5
+ # Licensed under the Apache License, Version 2.0 (the "License");
6
+ # you may not use this file except in compliance with the License.
7
+ # You may obtain a copy of the License at
8
+ #
9
+ # http://www.apache.org/licenses/LICENSE-2.0
10
+ #
11
+ # Unless required by applicable law or agreed to in writing, software
12
+ # distributed under the License is distributed on an "AS IS" BASIS,
13
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ # See the License for the specific language governing permissions and
15
+ # limitations under the License.
16
+ #
17
+
18
+ module ChefConfig
19
+
20
+ end
@@ -1,1124 +1,1125 @@
1
- #
2
- # Author:: Adam Jacob (<adam@chef.io>)
3
- # Author:: Christopher Brown (<cb@chef.io>)
4
- # Author:: AJ Christensen (<aj@chef.io>)
5
- # Author:: Mark Mzyk (<mmzyk@chef.io>)
6
- # Author:: Kyle Goodwin (<kgoodwin@primerevenue.com>)
7
- # Copyright:: Copyright 2008-2018, Chef Software Inc.
8
- # License:: Apache License, Version 2.0
9
- #
10
- # Licensed under the Apache License, Version 2.0 (the "License");
11
- # you may not use this file except in compliance with the License.
12
- # You may obtain a copy of the License at
13
- #
14
- # http://www.apache.org/licenses/LICENSE-2.0
15
- #
16
- # Unless required by applicable law or agreed to in writing, software
17
- # distributed under the License is distributed on an "AS IS" BASIS,
18
- # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
19
- # See the License for the specific language governing permissions and
20
- # limitations under the License.
21
-
22
- require "mixlib/config"
23
- require "pathname"
24
-
25
- require "chef-config/fips"
26
- require "chef-config/logger"
27
- require "chef-config/windows"
28
- require "chef-config/path_helper"
29
- require "chef-config/mixin/fuzzy_hostname_matcher"
30
-
31
- require "mixlib/shellout"
32
- require "uri"
33
- require "addressable/uri"
34
- require "openssl"
35
- require "yaml"
36
-
37
- module ChefConfig
38
-
39
- class Config
40
-
41
- extend Mixlib::Config
42
- extend ChefConfig::Mixin::FuzzyHostnameMatcher
43
-
44
- # Evaluates the given string as config.
45
- #
46
- # +filename+ is used for context in stacktraces, but doesn't need to be the name of an actual file.
47
- def self.from_string(string, filename)
48
- instance_eval(string, filename, 1)
49
- end
50
-
51
- def self.inspect
52
- configuration.inspect
53
- end
54
-
55
- # given a *nix style config path return the platform specific path
56
- # to that same config file
57
- # @example client.pem path on Windows
58
- # platform_specific_path("/etc/chef/client.pem") #=> "C:\\chef\\client.pem"
59
- # @param path [String] The unix path to convert to a platform specific path
60
- # @return [String] a platform specific path
61
- def self.platform_specific_path(path)
62
- path = PathHelper.cleanpath(path)
63
- if ChefConfig.windows?
64
- # turns \etc\chef\client.rb and \var\chef\client.rb into C:/chef/client.rb
65
- # Some installations will be on different drives so use the drive that
66
- # the expanded path to __FILE__ is found.
67
- drive = windows_installation_drive
68
- if drive && path[0] == '\\' && path.split('\\')[2] == "chef"
69
- path = PathHelper.join(drive, path.split('\\', 3)[2])
70
- end
71
- end
72
- path
73
- end
74
-
75
- # the drive where Chef is installed on a windows host. This is determined
76
- # either by the drive containing the current file or by the SYSTEMDRIVE ENV
77
- # variable
78
- #
79
- # @return [String] the drive letter
80
- def self.windows_installation_drive
81
- if ChefConfig.windows?
82
- drive = File.expand_path(__FILE__).split("/", 2)[0]
83
- drive = ENV["SYSTEMDRIVE"] if drive.to_s == ""
84
- drive
85
- end
86
- end
87
-
88
- def self.add_formatter(name, file_path = nil)
89
- formatters << [name, file_path]
90
- end
91
-
92
- def self.add_event_logger(logger)
93
- event_handlers << logger
94
- end
95
-
96
- def self.apply_extra_config_options(extra_config_options)
97
- if extra_config_options
98
- extra_parsed_options = extra_config_options.inject({}) do |memo, option|
99
- # Sanity check value.
100
- if option.empty? || !option.include?("=")
101
- raise UnparsableConfigOption, "Unparsable config option #{option.inspect}"
102
- end
103
- # Split including whitespace if someone does truly odd like
104
- # --config-option "foo = bar"
105
- key, value = option.split(/\s*=\s*/, 2)
106
- # Call to_sym because Chef::Config expects only symbol keys. Also
107
- # runs a simple parse on the string for some common types.
108
- memo[key.to_sym] = YAML.safe_load(value)
109
- memo
110
- end
111
- merge!(extra_parsed_options)
112
- end
113
- end
114
-
115
- # Config file to load (client.rb, knife.rb, etc. defaults set differently in knife, chef-client, etc.)
116
- configurable(:config_file)
117
-
118
- default(:config_dir) do
119
- if config_file
120
- PathHelper.dirname(PathHelper.canonical_path(config_file, false))
121
- else
122
- PathHelper.join(user_home, ".chef", "")
123
- end
124
- end
125
-
126
- default :formatters, []
127
-
128
- def self.is_valid_url?(uri)
129
- url = uri.to_s.strip
130
- /^http:\/\// =~ url || /^https:\/\// =~ url || /^chefzero:/ =~ url
131
- end
132
- # Override the config dispatch to set the value of multiple server options simultaneously
133
- #
134
- # === Parameters
135
- # url<String>:: String to be set for all of the chef-server-api URL's
136
- #
137
- configurable(:chef_server_url).writes_value do |uri|
138
- unless is_valid_url? uri
139
- raise ConfigurationError, "#{uri} is an invalid chef_server_url."
140
- end
141
- uri.to_s.strip
142
- end
143
-
144
- # When you are using ActiveSupport, they monkey-patch 'daemonize' into Kernel.
145
- # So while this is basically identical to what method_missing would do, we pull
146
- # it up here and get a real method written so that things get dispatched
147
- # properly.
148
- configurable(:daemonize).writes_value { |v| v }
149
-
150
- # The root where all local chef object data is stored. cookbooks, data bags,
151
- # environments are all assumed to be in separate directories under this.
152
- # chef-solo uses these directories for input data. knife commands
153
- # that upload or download files (such as knife upload, knife role from file,
154
- # etc.) work.
155
- default :chef_repo_path do
156
- if configuration[:cookbook_path]
157
- if configuration[:cookbook_path].kind_of?(String)
158
- File.expand_path("..", configuration[:cookbook_path])
159
- else
160
- configuration[:cookbook_path].map do |path|
161
- File.expand_path("..", path)
162
- end
163
- end
164
- elsif configuration[:cookbook_artifact_path]
165
- File.expand_path("..", configuration[:cookbook_artifact_path])
166
- else
167
- cache_path
168
- end
169
- end
170
-
171
- def self.find_chef_repo_path(cwd)
172
- # In local mode, we auto-discover the repo root by looking for a path with "cookbooks" under it.
173
- # This allows us to run config-free.
174
- path = cwd
175
- until File.directory?(PathHelper.join(path, "cookbooks")) || File.directory?(PathHelper.join(path, "cookbook_artifacts"))
176
- new_path = File.expand_path("..", path)
177
- if new_path == path
178
- ChefConfig.logger.warn("No cookbooks directory found at or above current directory. Assuming #{cwd}.")
179
- return cwd
180
- end
181
- path = new_path
182
- end
183
- ChefConfig.logger.info("Auto-discovered chef repository at #{path}")
184
- path
185
- end
186
-
187
- def self.derive_path_from_chef_repo_path(child_path)
188
- if chef_repo_path.kind_of?(String)
189
- PathHelper.join(chef_repo_path, child_path)
190
- else
191
- chef_repo_path.uniq.map { |path| PathHelper.join(path, child_path) }
192
- end
193
- end
194
-
195
- # Location of acls on disk. String or array of strings.
196
- # Defaults to <chef_repo_path>/acls.
197
- default(:acl_path) { derive_path_from_chef_repo_path("acls") }
198
-
199
- # Location of clients on disk. String or array of strings.
200
- # Defaults to <chef_repo_path>/clients.
201
- default(:client_path) { derive_path_from_chef_repo_path("clients") }
202
-
203
- # Location of client keys on disk. String or array of strings.
204
- # Defaults to <chef_repo_path>/client_keys.
205
- default(:client_key_path) { derive_path_from_chef_repo_path("client_keys") }
206
-
207
- # Location of containers on disk. String or array of strings.
208
- # Defaults to <chef_repo_path>/containers.
209
- default(:container_path) { derive_path_from_chef_repo_path("containers") }
210
-
211
- # Location of cookbook_artifacts on disk. String or array of strings.
212
- # Defaults to <chef_repo_path>/cookbook_artifacts.
213
- default(:cookbook_artifact_path) { derive_path_from_chef_repo_path("cookbook_artifacts") }
214
-
215
- # Location of cookbooks on disk. String or array of strings.
216
- # Defaults to <chef_repo_path>/cookbooks. If chef_repo_path
217
- # is not specified, this is set to [/var/chef/cookbooks, /var/chef/site-cookbooks]).
218
- default(:cookbook_path) do
219
- if configuration[:chef_repo_path]
220
- derive_path_from_chef_repo_path("cookbooks")
221
- else
222
- Array(derive_path_from_chef_repo_path("cookbooks")).flatten +
223
- Array(derive_path_from_chef_repo_path("site-cookbooks")).flatten
224
- end
225
- end
226
-
227
- # Location of data bags on disk. String or array of strings.
228
- # Defaults to <chef_repo_path>/data_bags.
229
- default(:data_bag_path) { derive_path_from_chef_repo_path("data_bags") }
230
-
231
- # Location of environments on disk. String or array of strings.
232
- # Defaults to <chef_repo_path>/environments.
233
- default(:environment_path) { derive_path_from_chef_repo_path("environments") }
234
-
235
- # Location of groups on disk. String or array of strings.
236
- # Defaults to <chef_repo_path>/groups.
237
- default(:group_path) { derive_path_from_chef_repo_path("groups") }
238
-
239
- # Location of nodes on disk. String or array of strings.
240
- # Defaults to <chef_repo_path>/nodes.
241
- default(:node_path) { derive_path_from_chef_repo_path("nodes") }
242
-
243
- # Location of policies on disk. String or array of strings.
244
- # Defaults to <chef_repo_path>/policies.
245
- default(:policy_path) { derive_path_from_chef_repo_path("policies") }
246
-
247
- # Location of policy_groups on disk. String or array of strings.
248
- # Defaults to <chef_repo_path>/policy_groups.
249
- default(:policy_group_path) { derive_path_from_chef_repo_path("policy_groups") }
250
-
251
- # Location of roles on disk. String or array of strings.
252
- # Defaults to <chef_repo_path>/roles.
253
- default(:role_path) { derive_path_from_chef_repo_path("roles") }
254
-
255
- # Location of users on disk. String or array of strings.
256
- # Defaults to <chef_repo_path>/users.
257
- default(:user_path) { derive_path_from_chef_repo_path("users") }
258
-
259
- # Location of policies on disk. String or array of strings.
260
- # Defaults to <chef_repo_path>/policies.
261
- default(:policy_path) { derive_path_from_chef_repo_path("policies") }
262
-
263
- # Turn on "path sanity" by default.
264
- default :enforce_path_sanity, false
265
-
266
- # Formatted Chef Client output is a beta feature, disabled by default:
267
- default :formatter, "null"
268
-
269
- # The number of times the client should retry when registering with the server
270
- default :client_registration_retries, 5
271
-
272
- # An array of paths to search for knife exec scripts if they aren't in the current directory
273
- default :script_path, []
274
-
275
- # The root of all caches (checksums, cache and backup). If local mode is on,
276
- # this is under the user's home directory.
277
- default(:cache_path) do
278
- if local_mode
279
- PathHelper.join(config_dir, "local-mode-cache")
280
- else
281
- primary_cache_root = platform_specific_path("/var")
282
- primary_cache_path = platform_specific_path("/var/chef")
283
- # Use /var/chef as the cache path only if that folder exists and we can read and write
284
- # into it, or /var exists and we can read and write into it (we'll create /var/chef later).
285
- # Otherwise, we'll create .chef under the user's home directory and use that as
286
- # the cache path.
287
- unless path_accessible?(primary_cache_path) || path_accessible?(primary_cache_root)
288
- secondary_cache_path = PathHelper.join(user_home, ".chef")
289
- ChefConfig.logger.info("Unable to access cache at #{primary_cache_path}. Switching cache to #{secondary_cache_path}")
290
- secondary_cache_path
291
- else
292
- primary_cache_path
293
- end
294
- end
295
- end
296
-
297
- # Returns true only if the path exists and is readable and writeable for the user.
298
- def self.path_accessible?(path)
299
- File.exists?(path) && File.readable?(path) && File.writable?(path)
300
- end
301
-
302
- # Where cookbook files are stored on the server (by content checksum)
303
- default(:checksum_path) { PathHelper.join(cache_path, "checksums") }
304
-
305
- # Where chef's cache files should be stored
306
- default(:file_cache_path) { PathHelper.join(cache_path, "cache") }
307
-
308
- # Where backups of chef-managed files should go
309
- default(:file_backup_path) { PathHelper.join(cache_path, "backup") }
310
-
311
- # The chef-client (or solo) lockfile.
312
- #
313
- # If your `file_cache_path` resides on a NFS (or non-flock()-supporting
314
- # fs), it's recommended to set this to something like
315
- # '/tmp/chef-client-running.pid'
316
- default(:lockfile) { PathHelper.join(file_cache_path, "chef-client-running.pid") }
317
-
318
- ## Daemonization Settings ##
319
- # What user should Chef run as?
320
- default :user, nil
321
- default :group, nil
322
- default :umask, 0022
323
-
324
- # Valid log_levels are:
325
- # * :debug
326
- # * :info
327
- # * :warn
328
- # * :fatal
329
- # These work as you'd expect. There is also a special `:auto` setting.
330
- # When set to :auto, Chef will auto adjust the log verbosity based on
331
- # context. When a tty is available (usually because the user is running chef
332
- # in a console), the log level is set to :warn, and output formatters are
333
- # used as the primary mode of output. When a tty is not available, the
334
- # logger is the primary mode of output, and the log level is set to :info
335
- default :log_level, :auto
336
-
337
- # Logging location as either an IO stream or string representing log file path
338
- default :log_location, STDOUT
339
-
340
- # Using `force_formatter` causes chef to default to formatter output when STDOUT is not a tty
341
- default :force_formatter, false
342
-
343
- # Using `force_logger` causes chef to default to logger output when STDOUT is a tty
344
- default :force_logger, false
345
-
346
- # Using 'stream_execute_output' will have Chef always stream the execute output
347
- default :stream_execute_output, false
348
-
349
- # Using `show_download_progress` will display the overall progress
350
- # of a remote file download
351
- default :show_download_progress, false
352
- # How often to update the progress meter, in percent
353
- default :download_progress_interval, 10
354
-
355
- default :http_retry_count, 5
356
- default :http_retry_delay, 5
357
- # Whether or not to send the Authorization header again on http redirects.
358
- # As per the plan in https://github.com/chef/chef/pull/7006, this will be
359
- # False in Chef 14, True in Chef 15, and will be removed entirely in Chef 16.
360
- default :http_disable_auth_on_redirect, false
361
-
362
- default :interval, nil
363
- default :once, nil
364
- default :json_attribs, nil
365
- # toggle info level log items that can create a lot of output
366
- default :verbose_logging, true
367
- default :node_name, nil
368
- default :diff_disabled, false
369
- default :diff_filesize_threshold, 10000000
370
- default :diff_output_threshold, 1000000
371
- default :local_mode, false
372
-
373
- # Configures the mode of operation for ChefFS, which is applied to the
374
- # ChefFS-based knife commands and chef-client's local mode. (ChefFS-based
375
- # knife commands include: knife delete, knife deps, knife diff, knife down,
376
- # knife edit, knife list, knife show, knife upload, and knife xargs.)
377
- #
378
- # Valid values are:
379
- # * "static": ChefFS only manages objects that exist in a traditional Chef
380
- # Repo as of Chef 11.
381
- # * "everything": ChefFS manages all object types that existed on the OSS
382
- # Chef 11 server.
383
- # * "hosted_everything": ChefFS manages all object types as of the Chef 12
384
- # Server, including RBAC objects and Policyfile objects (new to Chef 12).
385
- default :repo_mode do
386
- if local_mode && !chef_zero.osc_compat
387
- "hosted_everything"
388
- elsif chef_server_url =~ /\/+organizations\/.+/
389
- "hosted_everything"
390
- else
391
- "everything"
392
- end
393
- end
394
-
395
- default :pid_file, nil
396
-
397
- # Whether Chef Zero local mode should bind to a port. All internal requests
398
- # will go through the socketless code path regardless, so the socket is
399
- # only needed if other processes will connect to the local mode server.
400
- default :listen, false
401
-
402
- config_context :chef_zero do
403
- config_strict_mode true
404
- default(:enabled) { ChefConfig::Config.local_mode }
405
- default :host, "localhost"
406
- default :port, 8889.upto(9999) # Will try ports from 8889-9999 until one works
407
-
408
- # When set to a String, Chef Zero disables multitenant support. This is
409
- # what you want when using Chef Zero to serve a single Chef Repo. Setting
410
- # this to `false` enables multi-tenant.
411
- default :single_org, "chef"
412
-
413
- # Whether Chef Zero should operate in a mode analogous to OSS Chef Server
414
- # 11 (true) or Chef Server 12 (false). Chef Zero can still serve
415
- # policyfile objects in Chef 11 mode, as long as `repo_mode` is set to
416
- # "hosted_everything". The primary differences are:
417
- # * Chef 11 mode doesn't support multi-tennant, so there is no
418
- # distinction between global and org-specific objects (since there are
419
- # no orgs).
420
- # * Chef 11 mode doesn't expose RBAC objects
421
- default :osc_compat, false
422
- end
423
- default :chef_server_url, "https://localhost:443"
424
-
425
- default(:chef_server_root) do
426
- # if the chef_server_url is a path to an organization, aka
427
- # 'some_url.../organizations/*' then remove the '/organization/*' by default
428
- if configuration[:chef_server_url] =~ /\/organizations\/\S*$/
429
- configuration[:chef_server_url].split("/")[0..-3].join("/")
430
- elsif configuration[:chef_server_url] # default to whatever chef_server_url is
431
- configuration[:chef_server_url]
432
- else
433
- "https://localhost:443"
434
- end
435
- end
436
-
437
- default :rest_timeout, 300
438
- default :yum_timeout, 900
439
- default :yum_lock_timeout, 30
440
- default :solo, false
441
-
442
- # Are we running in old Chef Solo legacy mode?
443
- default :solo_legacy_mode, false
444
-
445
- default :splay, nil
446
- default :why_run, false
447
- default :color, false
448
- default :client_fork, nil
449
- default :ez, false
450
- default :enable_reporting, true
451
- default :enable_reporting_url_fatals, false
452
- # Possible values for :audit_mode
453
- # :enabled, :disabled, :audit_only,
454
- #
455
- # TODO: 11 Dec 2014: Currently audit-mode is an experimental feature
456
- # and is disabled by default. When users choose to enable audit-mode,
457
- # a warning is issued in application/client#reconfigure.
458
- # This can be removed when audit-mode is enabled by default.
459
- default :audit_mode, :disabled
460
-
461
- # Chef only needs ohai to run the hostname plugin for the most basic
462
- # functionality. If the rest of the ohai plugins are not needed (like in
463
- # most of our testing scenarios)
464
- default :minimal_ohai, false
465
-
466
- # When consuming Ohai plugins from cookbook segments, we place those plugins in this directory.
467
- # Subsequent chef client runs will wipe and re-populate the directory to ensure cleanliness
468
- default(:ohai_segment_plugin_path) { PathHelper.join(config_dir, "ohai", "cookbook_plugins") }
469
-
470
- ###
471
- # Policyfile Settings
472
- #
473
- # Policyfile is a feature where a node gets its run list and cookbook
474
- # version set from a single document on the server instead of expanding the
475
- # run list and having the server compute the cookbook version set based on
476
- # environment constraints.
477
- #
478
- # Policyfiles are auto-versioned. The user groups nodes by `policy_name`,
479
- # which generally describes a hosts's functional role, and `policy_group`,
480
- # which generally groups nodes by deployment phase (a.k.a., "environment").
481
- # The Chef Server maps a given set of `policy_name` plus `policy_group` to
482
- # a particular revision of a policy.
483
-
484
- default :policy_name, nil
485
- default :policy_group, nil
486
-
487
- # Policyfiles can have multiple run lists, via the named run list feature.
488
- # Generally this will be set by a CLI option via Chef::Application::Client,
489
- # but it could be set in client.rb if desired.
490
-
491
- default :named_run_list, nil
492
-
493
- # During initial development, users were required to set `use_policyfile true`
494
- # in `client.rb` to opt-in to policyfile use. Chef Client now examines
495
- # configuration, node json, and the stored node to determine if policyfile
496
- # usage is desired. This flag is still honored if set, but is unnecessary.
497
- default :use_policyfile, false
498
-
499
- # Policyfiles can be used in a native mode (default) or compatibility mode.
500
- # Native mode requires Chef Server 12.1 (it can be enabled via feature flag
501
- # on some prior versions). In native mode, policies and associated
502
- # cookbooks are accessed via feature-specific APIs. In compat mode,
503
- # policies are stored as data bags and cookbooks are stored at the
504
- # cookbooks/ endpoint. Compatibility mode can be dangerous on existing Chef
505
- # Servers; it's recommended to upgrade your Chef Server rather than use
506
- # compatibility mode. Compatibility mode remains available so you can use
507
- # policyfiles with servers that don't yet support the native endpoints.
508
- default :policy_document_native_api, true
509
-
510
- # When policyfiles are used in compatibility mode, `policy_name` and
511
- # `policy_group` are instead specified using a combined configuration
512
- # setting, `deployment_group`. For example, if policy_name should be
513
- # "webserver" and policy_group should be "staging", then `deployment_group`
514
- # should be set to "webserver-staging", which is the name of the data bag
515
- # item that the policy will be stored as. NOTE: this setting only has an
516
- # effect if `policy_document_native_api` is set to `false`.
517
- default :deployment_group, nil
518
-
519
- # Set these to enable SSL authentication / mutual-authentication
520
- # with the server
521
-
522
- # Client side SSL cert/key for mutual auth
523
- default :ssl_client_cert, nil
524
- default :ssl_client_key, nil
525
-
526
- # Whether or not to verify the SSL cert for all HTTPS requests. When set to
527
- # :verify_peer (default), all HTTPS requests will be validated regardless of other
528
- # SSL verification settings. When set to :verify_none no HTTPS requests will
529
- # be validated.
530
- default :ssl_verify_mode, :verify_peer
531
-
532
- # Whether or not to verify the SSL cert for HTTPS requests to the Chef
533
- # server API. If set to `true`, the server's cert will be validated
534
- # regardless of the :ssl_verify_mode setting. This is set to `true` when
535
- # running in local-mode.
536
- # NOTE: This is a workaround until verify_peer is enabled by default.
537
- default(:verify_api_cert) { ChefConfig::Config.local_mode }
538
-
539
- # Path to the default CA bundle files.
540
- default :ssl_ca_path, nil
541
- default(:ssl_ca_file) do
542
- if ChefConfig.windows? && embedded_dir
543
- cacert_path = File.join(embedded_dir, "ssl/certs/cacert.pem")
544
- cacert_path if File.exist?(cacert_path)
545
- else
546
- nil
547
- end
548
- end
549
-
550
- # A directory that contains additional SSL certificates to trust. Any
551
- # certificates in this directory will be added to whatever CA bundle ruby
552
- # is using. Use this to add self-signed certs for your Chef Server or local
553
- # HTTP file servers.
554
- default(:trusted_certs_dir) { PathHelper.join(config_dir, "trusted_certs") }
555
-
556
- # A directory that contains additional configuration scripts to load for chef-client
557
- default(:client_d_dir) { PathHelper.join(config_dir, "client.d") }
558
-
559
- # A directory that contains additional configuration scripts to load for solo
560
- default(:solo_d_dir) { PathHelper.join(config_dir, "solo.d") }
561
-
562
- # A directory that contains additional configuration scripts to load for
563
- # the workstation config
564
- default(:config_d_dir) { PathHelper.join(config_dir, "config.d") }
565
-
566
- # Where should chef-solo download recipes from?
567
- default :recipe_url, nil
568
-
569
- # Set to true if Chef is to set OpenSSL to run in FIPS mode
570
- default(:fips) do
571
- # CHEF_FIPS is used in testing to override checking for system level
572
- # enablement. There are 3 possible values that this variable may have:
573
- # nil - no override and the system will be checked
574
- # empty - FIPS is NOT enabled
575
- # a non empty value - FIPS is enabled
576
- if ENV["CHEF_FIPS"] == ""
577
- false
578
- else
579
- !ENV["CHEF_FIPS"].nil? || ChefConfig.fips?
580
- end
581
- end
582
-
583
- # Initialize openssl
584
- def self.init_openssl
585
- if fips
586
- enable_fips_mode
587
- end
588
- end
589
-
590
- # Sets the version of the signed header authentication protocol to use (see
591
- # the 'mixlib-authorization' project for more detail). Currently, versions
592
- # 1.0, 1.1, and 1.3 are available.
593
- default :authentication_protocol_version do
594
- if fips
595
- "1.3"
596
- else
597
- "1.1"
598
- end
599
- end
600
-
601
- # This key will be used to sign requests to the Chef server. This location
602
- # must be writable by Chef during initial setup when generating a client
603
- # identity on the server.
604
- #
605
- # The chef-server will look up the public key for the client using the
606
- # `node_name` of the client.
607
- #
608
- # If chef-zero is enabled, this defaults to nil (no authentication).
609
- default(:client_key) { chef_zero.enabled ? nil : platform_specific_path("/etc/chef/client.pem") }
610
-
611
- # A credentials file may contain a complete client key, rather than the path
612
- # to one.
613
- #
614
- # We'll use this preferentially.
615
- default :client_key_contents, nil
616
-
617
- # When registering the client, should we allow the client key location to
618
- # be a symlink? eg: /etc/chef/client.pem -> /etc/chef/prod-client.pem
619
- # If the path of the key goes through a directory like /tmp this should
620
- # never be set to true or its possibly an easily exploitable security hole.
621
- default :follow_client_key_symlink, false
622
-
623
- # This secret is used to decrypt encrypted data bag items.
624
- default(:encrypted_data_bag_secret) do
625
- if File.exist?(platform_specific_path("/etc/chef/encrypted_data_bag_secret"))
626
- platform_specific_path("/etc/chef/encrypted_data_bag_secret")
627
- else
628
- nil
629
- end
630
- end
631
-
632
- # As of Chef 13.0, version "3" is the default encrypted data bag item
633
- # format.
634
- #
635
- default :data_bag_encrypt_version, 3
636
-
637
- # When reading data bag items, any supported version is accepted. However,
638
- # if all encrypted data bags have been generated with the version 2 format,
639
- # it is recommended to disable support for earlier formats to improve
640
- # security. For example, the version 2 format is identical to version 1
641
- # except for the addition of an HMAC, so an attacker with MITM capability
642
- # could downgrade an encrypted data bag to version 1 as part of an attack.
643
- default :data_bag_decrypt_minimum_version, 0
644
-
645
- # If there is no file in the location given by `client_key`, chef-client
646
- # will temporarily use the "validator" identity to generate one. If the
647
- # `client_key` is not present and the `validation_key` is also not present,
648
- # chef-client will not be able to authenticate to the server.
649
- #
650
- # The `validation_key` is never used if the `client_key` exists.
651
- #
652
- # If chef-zero is enabled, this defaults to nil (no authentication).
653
- default(:validation_key) { chef_zero.enabled ? nil : platform_specific_path("/etc/chef/validation.pem") }
654
- default :validation_client_name, "chef-validator"
655
-
656
- default :validation_key_contents, nil
657
- # When creating a new client via the validation_client account, Chef 11
658
- # servers allow the client to generate a key pair locally and send the
659
- # public key to the server. This is more secure and helps offload work from
660
- # the server, enhancing scalability. If enabled and the remote server
661
- # implements only the Chef 10 API, client registration will not work
662
- # properly.
663
- #
664
- # The default value is `true`. Set to `false` to disable client-side key
665
- # generation (server generates client keys).
666
- default(:local_key_generation) { true }
667
-
668
- # Zypper package provider gpg checks. Set to false to disable package
669
- # gpg signature checking globally. This will warn you that it is a
670
- # bad thing to do.
671
- default :zypper_check_gpg, true
672
-
673
- # Report Handlers
674
- default :report_handlers, []
675
-
676
- # Event Handlers
677
- default :event_handlers, []
678
-
679
- default :disable_event_loggers, false
680
-
681
- # Exception Handlers
682
- default :exception_handlers, []
683
-
684
- # Start handlers
685
- default :start_handlers, []
686
-
687
- # Syntax Check Cache. Knife keeps track of files that is has already syntax
688
- # checked by storing files in this directory. `syntax_check_cache_path` is
689
- # the new (and preferred) configuration setting. If not set, knife will
690
- # fall back to using cache_options[:path], which is deprecated but exists in
691
- # many client configs generated by pre-Chef-11 bootstrappers.
692
- default(:syntax_check_cache_path) { cache_options[:path] }
693
-
694
- # Deprecated:
695
- # Move this to the default value of syntax_cache_path when this is removed.
696
- default(:cache_options) { { :path => PathHelper.join(config_dir, "syntaxcache") } }
697
-
698
- # Whether errors should be raised for deprecation warnings. When set to
699
- # `false` (the default setting), a warning is emitted but code using
700
- # deprecated methods/features/etc. should work normally otherwise. When set
701
- # to `true`, usage of deprecated methods/features will raise a
702
- # `DeprecatedFeatureError`. This is used by Chef's tests to ensure that
703
- # deprecated functionality is not used internally by Chef. End users
704
- # should generally leave this at the default setting (especially in
705
- # production), but it may be useful when testing cookbooks or other code if
706
- # the user wishes to aggressively address deprecations.
707
- default(:treat_deprecation_warnings_as_errors) do
708
- # Using an environment variable allows this setting to be inherited in
709
- # tests that spawn new processes.
710
- ENV.key?("CHEF_TREAT_DEPRECATION_WARNINGS_AS_ERRORS")
711
- end
712
-
713
- # Whether the resource count should be updated for log resource
714
- # on running chef-client
715
- default :count_log_resource_updates, true
716
-
717
- # The selected profile when using credentials.
718
- default :profile, nil
719
-
720
- default :chef_guid_path do
721
- PathHelper.join(config_dir, "chef_guid")
722
- end
723
-
724
- default :chef_guid, nil
725
-
726
- # knife configuration data
727
- config_context :knife do
728
- # XXX: none of these default values are applied to knife (and would create a backcompat
729
- # break in knife if this bug was fixed since many of the defaults below are wrong). this appears
730
- # to be the start of an attempt to be able to use config_strict_mode true? if so, this approach
731
- # is fraught with peril because this namespace is used by every knife plugin in the wild and
732
- # we would need to validate every cli option in every knife attribute out there and list them all here.
733
- #
734
- # based on the way that people may define `knife[:foobar] = "something"` for the knife-foobar
735
- # gem plugin i'm pretty certain we can never turn on anything like config_string_mode since
736
- # any config value may be a typo or it may be in some gem in some knife plugin we don't know about.
737
- #
738
- # we do still need to maintain at least one of these so that the knife config hash gets
739
- # created.
740
- #
741
- # this whole situation is deeply unsatisfying.
742
- default :ssh_port, nil
743
- default :ssh_user, nil
744
- default :ssh_attribute, nil
745
- default :ssh_gateway, nil
746
- default :ssh_gateway_identity, nil
747
- default :bootstrap_version, nil
748
- default :bootstrap_proxy, nil
749
- default :bootstrap_template, nil
750
- default :secret, nil
751
- default :secret_file, nil
752
- default :identity_file, nil
753
- default :host_key_verify, nil
754
- default :forward_agent, nil
755
- default :sort_status_reverse, nil
756
- default :hints, {}
757
- end
758
-
759
- def self.set_defaults_for_windows
760
- # Those lists of regular expressions define what chef considers a
761
- # valid user and group name
762
- # From http://technet.microsoft.com/en-us/library/cc776019(WS.10).aspx
763
- principal_valid_regex_part = '[^"\/\\\\\[\]\:;|=,+*?<>]+'
764
- default :user_valid_regex, [ /^(#{principal_valid_regex_part}\\)?#{principal_valid_regex_part}$/ ]
765
- default :group_valid_regex, [ /^(#{principal_valid_regex_part}\\)?#{principal_valid_regex_part}$/ ]
766
-
767
- default :fatal_windows_admin_check, false
768
- end
769
-
770
- def self.set_defaults_for_nix
771
- # Those lists of regular expressions define what chef considers a
772
- # valid user and group name
773
- #
774
- # user/group cannot start with '-', '+' or '~'
775
- # user/group cannot contain ':', ',' or non-space-whitespace or null byte
776
- # everything else is allowed (UTF-8, spaces, etc) and we delegate to your O/S useradd program to barf or not
777
- # copies: http://anonscm.debian.org/viewvc/pkg-shadow/debian/trunk/debian/patches/506_relaxed_usernames?view=markup
778
- default :user_valid_regex, [ /^[^-+~:,\t\r\n\f\0]+[^:,\t\r\n\f\0]*$/ ]
779
- default :group_valid_regex, [ /^[^-+~:,\t\r\n\f\0]+[^:,\t\r\n\f\0]*$/ ]
780
- end
781
-
782
- # Those lists of regular expressions define what chef considers a
783
- # valid user and group name
784
- if ChefConfig.windows?
785
- set_defaults_for_windows
786
- else
787
- set_defaults_for_nix
788
- end
789
-
790
- # This provides a hook which rspec can stub so that we can avoid twiddling
791
- # global state in tests.
792
- def self.env
793
- ENV
794
- end
795
-
796
- def self.windows_home_path
797
- ChefConfig.logger.deprecation("Chef::Config.windows_home_path is now deprecated. Consider using Chef::Util::PathHelper.home instead.")
798
- PathHelper.home
799
- end
800
-
801
- # returns a platform specific path to the user home dir if set, otherwise default to current directory.
802
- default( :user_home ) { PathHelper.home || Dir.pwd }
803
-
804
- # Enable file permission fixup for selinux. Fixup will be done
805
- # only if selinux is enabled in the system.
806
- default :enable_selinux_file_permission_fixup, true
807
-
808
- # Use atomic updates (i.e. move operation) while updating contents
809
- # of the files resources. When set to false copy operation is
810
- # used to update files.
811
- #
812
- # NOTE: CHANGING THIS SETTING MAY CAUSE CORRUPTION, DATA LOSS AND
813
- # INSTABILITY.
814
- default :file_atomic_update, true
815
-
816
- # There are 3 possible values for this configuration setting.
817
- # true => file staging is done in the destination directory
818
- # false => file staging is done via tempfiles under ENV['TMP']
819
- # :auto => file staging will try using destination directory if possible and
820
- # will fall back to ENV['TMP'] if destination directory is not usable.
821
- default :file_staging_uses_destdir, :auto
822
-
823
- # Exit if another run is in progress and the chef-client is unable to
824
- # get the lock before time expires. If nil, no timeout is enforced. (Exits
825
- # immediately if 0.)
826
- default :run_lock_timeout, nil
827
-
828
- # Number of worker threads for syncing cookbooks in parallel. Increasing
829
- # this number can result in gateway errors from the server (namely 503 and 504).
830
- # If you are seeing this behavior while using the default setting, reducing
831
- # the number of threads will help.
832
- default :cookbook_sync_threads, 10
833
-
834
- # At the beginning of the Chef Client run, the cookbook manifests are downloaded which
835
- # contain URLs for every file in every relevant cookbook. Most of the files
836
- # (recipes, resources, providers, libraries, etc) are immediately synchronized
837
- # at the start of the run. The handling of "files" and "templates" directories,
838
- # however, have two modes of operation. They can either all be downloaded immediately
839
- # at the start of the run (no_lazy_load==true) or else they can be lazily loaded as
840
- # cookbook_file or template resources are converged which require them (no_lazy_load==false).
841
- #
842
- # The advantage of lazily loading these files is that unnecessary files are not
843
- # synchronized. This may be useful to users with large files checked into cookbooks which
844
- # are only selectively downloaded to a subset of clients which use the cookbook. However,
845
- # better solutions are to either isolate large files into individual cookbooks and only
846
- # include those cookbooks in the run lists of the servers that need them -- or move to
847
- # using remote_file and a more appropriate backing store like S3 for large file
848
- # distribution.
849
- #
850
- # The disadvantages of lazily loading files are that users some time find it
851
- # confusing that their cookbooks are not fully synchronzied to the cache initially,
852
- # and more importantly the time-sensitive URLs which are in the manifest may time
853
- # out on long Chef runs before the resource that uses the file is converged
854
- # (leading to many confusing 403 errors on template/cookbook_file resources).
855
- #
856
- default :no_lazy_load, true
857
-
858
- # A whitelisted array of attributes you want sent over the wire when node
859
- # data is saved.
860
- # The default setting is nil, which collects all data. Setting to [] will not
861
- # collect any data for save.
862
- default :automatic_attribute_whitelist, nil
863
- default :default_attribute_whitelist, nil
864
- default :normal_attribute_whitelist, nil
865
- default :override_attribute_whitelist, nil
866
-
867
- # A blacklisted array of attributes you do not want to send over the
868
- # wire when node data is saved
869
- # The default setting is nil, which collects all data. Setting to [] will
870
- # still collect all data for save
871
- default :automatic_attribute_blacklist, nil
872
- default :default_attribute_blacklist, nil
873
- default :normal_attribute_blacklist, nil
874
- default :override_attribute_blacklist, nil
875
-
876
- # Pull down all the rubygems versions from rubygems and cache them the first time we do a gem_package or
877
- # chef_gem install. This is memory-expensive and will grow without bounds, but will reduce network
878
- # round trips.
879
- default :rubygems_cache_enabled, false
880
-
881
- config_context :windows_service do
882
- # Set `watchdog_timeout` to the number of seconds to wait for a chef-client run
883
- # to finish
884
- default :watchdog_timeout, 2 * (60 * 60) # 2 hours
885
- end
886
-
887
- # Add an empty and non-strict config_context for chefdk. This lets the user
888
- # have code like `chefdk.generator_cookbook "/path/to/cookbook"` in their
889
- # config.rb, and it will be ignored by tools like knife and ohai. ChefDK
890
- # itself can define the config options it accepts and enable strict mode,
891
- # and that will only apply when running `chef` commands.
892
- config_context :chefdk do
893
- end
894
-
895
- # Configuration options for Data Collector reporting. These settings allow
896
- # the user to configure where to send their Data Collector data, what token
897
- # to send, and whether Data Collector should report its findings in client
898
- # mode vs. solo mode.
899
- config_context :data_collector do
900
- # Full URL to the endpoint that will receive our data. If nil, the
901
- # data collector will not run.
902
- # Ex: http://my-data-collector.mycompany.com/ingest
903
- default(:server_url) do
904
- if config_parent.solo || config_parent.local_mode
905
- nil
906
- else
907
- File.join(config_parent.chef_server_url, "/data-collector")
908
- end
909
- end
910
-
911
- # An optional pre-shared token to pass as an HTTP header (x-data-collector-token)
912
- # that can be used to determine whether or not the poster of this
913
- # run data should be trusted.
914
- # Ex: some-uuid-here
915
- default :token, nil
916
-
917
- # The Chef mode during which Data Collector is allowed to function. This
918
- # can be used to run Data Collector only when running as Chef Solo but
919
- # not when using Chef Client.
920
- # Options: :solo (for both Solo Legacy Mode and Client Local Mode), :client, :both
921
- default :mode, :both
922
-
923
- # When the Data Collector cannot send the "starting a run" message to
924
- # the Data Collector server, the Data Collector will be disabled for that
925
- # run. In some situations, such as highly-regulated environments, it
926
- # may be more reasonable to prevent Chef from performing the actual run.
927
- # In these situations, setting this value to true will cause the Chef
928
- # run to raise an exception before starting any converge activities.
929
- default :raise_on_failure, false
930
-
931
- # A user-supplied Organization string that can be sent in payloads
932
- # generated by the DataCollector when Chef is run in Solo mode. This
933
- # allows users to associate their Solo nodes with faux organizations
934
- # without the nodes being connected to an actual Chef Server.
935
- default :organization, nil
936
- end
937
-
938
- configurable(:http_proxy)
939
- configurable(:http_proxy_user)
940
- configurable(:http_proxy_pass)
941
- configurable(:https_proxy)
942
- configurable(:https_proxy_user)
943
- configurable(:https_proxy_pass)
944
- configurable(:ftp_proxy)
945
- configurable(:ftp_proxy_user)
946
- configurable(:ftp_proxy_pass)
947
- configurable(:no_proxy)
948
-
949
- # Public method that users should call to export proxies to the appropriate
950
- # environment variables. This method should be called after the config file is
951
- # parsed and loaded.
952
- # TODO add some post-file-parsing logic that automatically calls this so
953
- # users don't have to
954
- def self.export_proxies
955
- export_proxy("http", http_proxy, http_proxy_user, http_proxy_pass) if http_proxy
956
- export_proxy("https", https_proxy, https_proxy_user, https_proxy_pass) if https_proxy
957
- export_proxy("ftp", ftp_proxy, ftp_proxy_user, ftp_proxy_pass) if ftp_proxy
958
- export_no_proxy(no_proxy) if no_proxy
959
- end
960
-
961
- # Character classes for Addressable
962
- # See https://www.ietf.org/rfc/rfc3986.txt 3.2.1
963
- # The user part may not have a : in it
964
- USER = Addressable::URI::CharacterClasses::UNRESERVED + Addressable::URI::CharacterClasses::SUB_DELIMS
965
- # The password part may have any valid USERINFO characters
966
- PASSWORD = USER + "\\:"
967
-
968
- # Builds a proxy uri and exports it to the appropriate environment variables. Examples:
969
- # http://username:password@hostname:port
970
- # https://username@hostname:port
971
- # ftp://hostname:port
972
- # when
973
- # scheme = "http", "https", or "ftp"
974
- # hostport = hostname:port or scheme://hostname:port
975
- # user = username
976
- # pass = password
977
- # @api private
978
- def self.export_proxy(scheme, path, user, pass)
979
- path = "#{scheme}://#{path}" unless path.include?("://")
980
- # URI.split returns the following parts:
981
- # [scheme, userinfo, host, port, registry, path, opaque, query, fragment]
982
- uri = Addressable::URI.encode(path, Addressable::URI)
983
-
984
- if user && !user.empty?
985
- userinfo = Addressable::URI.encode_component(user, USER)
986
- if pass
987
- userinfo << ":#{Addressable::URI.encode_component(pass, PASSWORD)}"
988
- end
989
- uri.userinfo = userinfo
990
- end
991
-
992
- path = uri.to_s
993
- ENV["#{scheme}_proxy".downcase] = path unless ENV["#{scheme}_proxy".downcase]
994
- ENV["#{scheme}_proxy".upcase] = path unless ENV["#{scheme}_proxy".upcase]
995
- end
996
-
997
- # @api private
998
- def self.export_no_proxy(value)
999
- ENV["no_proxy"] = value unless ENV["no_proxy"]
1000
- ENV["NO_PROXY"] = value unless ENV["NO_PROXY"]
1001
- end
1002
-
1003
- # Given a scheme, host, and port, return the correct proxy URI based on the
1004
- # set environment variables, unless exluded by no_proxy, in which case nil
1005
- # is returned
1006
- def self.proxy_uri(scheme, host, port)
1007
- proxy_env_var = ENV["#{scheme}_proxy"].to_s.strip
1008
-
1009
- # Check if the proxy string contains a scheme. If not, add the url's scheme to the
1010
- # proxy before parsing. The regex /^.*:\/\// matches, for example, http://. Reusing proxy
1011
- # here since we are really just trying to get the string built correctly.
1012
- proxy = if !proxy_env_var.empty?
1013
- if proxy_env_var =~ /^.*:\/\//
1014
- URI.parse(proxy_env_var)
1015
- else
1016
- URI.parse("#{scheme}://#{proxy_env_var}")
1017
- end
1018
- end
1019
-
1020
- return proxy unless fuzzy_hostname_match_any?(host, ENV["no_proxy"])
1021
- end
1022
-
1023
- # Chef requires an English-language UTF-8 locale to function properly. We attempt
1024
- # to use the 'locale -a' command and search through a list of preferences until we
1025
- # find one that we can use. On Ubuntu systems we should find 'C.UTF-8' and be
1026
- # able to use that even if there is no English locale on the server, but Mac, Solaris,
1027
- # AIX, etc do not have that locale. We then try to find an English locale and fall
1028
- # back to 'C' if we do not. The choice of fallback is pick-your-poison. If we try
1029
- # to do the work to return a non-US UTF-8 locale then we fail inside of providers when
1030
- # things like 'svn info' return Japanese and we can't parse them. OTOH, if we pick 'C' then
1031
- # we will blow up on UTF-8 characters. Between the warn we throw and the Encoding
1032
- # exception that ruby will throw it is more obvious what is broken if we drop UTF-8 by
1033
- # default rather than drop English.
1034
- #
1035
- # If there is no 'locale -a' then we return 'en_US.UTF-8' since that is the most commonly
1036
- # available English UTF-8 locale. However, all modern POSIXen should support 'locale -a'.
1037
- def self.guess_internal_locale
1038
- # https://github.com/chef/chef/issues/2181
1039
- # Some systems have the `locale -a` command, but the result has
1040
- # invalid characters for the default encoding.
1041
- #
1042
- # For example, on CentOS 6 with ENV['LANG'] = "en_US.UTF-8",
1043
- # `locale -a`.split fails with ArgumentError invalid UTF-8 encoding.
1044
- cmd = Mixlib::ShellOut.new("locale -a").run_command
1045
- cmd.error!
1046
- locales = cmd.stdout.split
1047
- case
1048
- when locales.include?("C.UTF-8")
1049
- "C.UTF-8"
1050
- when locales.include?("en_US.UTF-8"), locales.include?("en_US.utf8")
1051
- "en_US.UTF-8"
1052
- when locales.include?("en.UTF-8")
1053
- "en.UTF-8"
1054
- else
1055
- # Will match en_ZZ.UTF-8, en_ZZ.utf-8, en_ZZ.UTF8, en_ZZ.utf8
1056
- guesses = locales.select { |l| l =~ /^en_.*UTF-?8$/i }
1057
- unless guesses.empty?
1058
- guessed_locale = guesses.first
1059
- # Transform into the form en_ZZ.UTF-8
1060
- guessed_locale.gsub(/UTF-?8$/i, "UTF-8")
1061
- else
1062
- ChefConfig.logger.warn "Please install an English UTF-8 locale for Chef to use, falling back to C locale and disabling UTF-8 support."
1063
- "C"
1064
- end
1065
- end
1066
- rescue
1067
- if ChefConfig.windows?
1068
- ChefConfig.logger.trace "Defaulting to locale en_US.UTF-8 on Windows, until it matters that we do something else."
1069
- else
1070
- ChefConfig.logger.trace "No usable locale -a command found, assuming you have en_US.UTF-8 installed."
1071
- end
1072
- "en_US.UTF-8"
1073
- end
1074
-
1075
- default :internal_locale, guess_internal_locale
1076
-
1077
- # Force UTF-8 Encoding, for when we fire up in the 'C' locale or other strange locales (e.g.
1078
- # japanese windows encodings). If we do not do this, then knife upload will fail when a cookbook's
1079
- # README.md has UTF-8 characters that do not encode in whatever surrounding encoding we have been
1080
- # passed. Effectively, the Chef Ecosystem is globally UTF-8 by default. Anyone who wants to be
1081
- # able to upload Shift_JIS or ISO-8859-1 files needs to mark *those* files explicitly with
1082
- # magic tags to make ruby correctly identify the encoding being used. Changing this default will
1083
- # break Chef community cookbooks and is very highly discouraged.
1084
- default :ruby_encoding, Encoding::UTF_8
1085
-
1086
- # can be set to a string or array of strings for URIs to set as rubygems sources
1087
- default :rubygems_url, "https://www.rubygems.org"
1088
-
1089
- # If installed via an omnibus installer, this gives the path to the
1090
- # "embedded" directory which contains all of the software packaged with
1091
- # omnibus. This is used to locate the cacert.pem file on windows.
1092
- def self.embedded_dir
1093
- Pathname.new(_this_file).ascend do |path|
1094
- if path.basename.to_s == "embedded"
1095
- return path.to_s
1096
- end
1097
- end
1098
-
1099
- nil
1100
- end
1101
-
1102
- # Path to this file in the current install.
1103
- def self._this_file
1104
- File.expand_path(__FILE__)
1105
- end
1106
-
1107
- # Set fips mode in openssl. Do any patching necessary to make
1108
- # sure Chef runs do not crash.
1109
- # @api private
1110
- def self.enable_fips_mode
1111
- OpenSSL.fips_mode = true
1112
- require "digest"
1113
- require "digest/sha1"
1114
- require "digest/md5"
1115
- # Remove pre-existing constants if they do exist to reduce the
1116
- # amount of log spam and warnings.
1117
- Digest.send(:remove_const, "SHA1") if Digest.const_defined?("SHA1")
1118
- Digest.const_set("SHA1", OpenSSL::Digest::SHA1)
1119
- OpenSSL::Digest.send(:remove_const, "MD5") if OpenSSL::Digest.const_defined?("MD5")
1120
- OpenSSL::Digest.const_set("MD5", Digest::MD5)
1121
- ChefConfig.logger.debug "FIPS mode is enabled."
1122
- end
1123
- end
1124
- end
1
+ #
2
+ # Author:: Adam Jacob (<adam@chef.io>)
3
+ # Author:: Christopher Brown (<cb@chef.io>)
4
+ # Author:: AJ Christensen (<aj@chef.io>)
5
+ # Author:: Mark Mzyk (<mmzyk@chef.io>)
6
+ # Author:: Kyle Goodwin (<kgoodwin@primerevenue.com>)
7
+ # Copyright:: Copyright 2008-2018, Chef Software Inc.
8
+ # License:: Apache License, Version 2.0
9
+ #
10
+ # Licensed under the Apache License, Version 2.0 (the "License");
11
+ # you may not use this file except in compliance with the License.
12
+ # You may obtain a copy of the License at
13
+ #
14
+ # http://www.apache.org/licenses/LICENSE-2.0
15
+ #
16
+ # Unless required by applicable law or agreed to in writing, software
17
+ # distributed under the License is distributed on an "AS IS" BASIS,
18
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
19
+ # See the License for the specific language governing permissions and
20
+ # limitations under the License.
21
+
22
+ require "mixlib/config"
23
+ require "pathname"
24
+
25
+ require "chef-config/fips"
26
+ require "chef-config/logger"
27
+ require "chef-config/windows"
28
+ require "chef-config/path_helper"
29
+ require "chef-config/mixin/fuzzy_hostname_matcher"
30
+
31
+ require "mixlib/shellout"
32
+ require "uri"
33
+ require "addressable/uri"
34
+ require "openssl"
35
+ require "yaml"
36
+
37
+ module ChefConfig
38
+
39
+ class Config
40
+
41
+ extend Mixlib::Config
42
+ extend ChefConfig::Mixin::FuzzyHostnameMatcher
43
+
44
+ # Evaluates the given string as config.
45
+ #
46
+ # +filename+ is used for context in stacktraces, but doesn't need to be the name of an actual file.
47
+ def self.from_string(string, filename)
48
+ instance_eval(string, filename, 1)
49
+ end
50
+
51
+ def self.inspect
52
+ configuration.inspect
53
+ end
54
+
55
+ # given a *nix style config path return the platform specific path
56
+ # to that same config file
57
+ # @example client.pem path on Windows
58
+ # platform_specific_path("/etc/chef/client.pem") #=> "C:\\chef\\client.pem"
59
+ # @param path [String] The unix path to convert to a platform specific path
60
+ # @return [String] a platform specific path
61
+ def self.platform_specific_path(path)
62
+ path = PathHelper.cleanpath(path)
63
+ if ChefConfig.windows?
64
+ # turns \etc\chef\client.rb and \var\chef\client.rb into C:/chef/client.rb
65
+ # Some installations will be on different drives so use the drive that
66
+ # the expanded path to __FILE__ is found.
67
+ drive = windows_installation_drive
68
+ if drive && path[0] == '\\' && path.split('\\')[2] == "chef"
69
+ path = PathHelper.join(drive, path.split('\\', 3)[2])
70
+ end
71
+ end
72
+ path
73
+ end
74
+
75
+ # the drive where Chef is installed on a windows host. This is determined
76
+ # either by the drive containing the current file or by the SYSTEMDRIVE ENV
77
+ # variable
78
+ #
79
+ # @return [String] the drive letter
80
+ def self.windows_installation_drive
81
+ if ChefConfig.windows?
82
+ drive = File.expand_path(__FILE__).split("/", 2)[0]
83
+ drive = ENV["SYSTEMDRIVE"] if drive.to_s == ""
84
+ drive
85
+ end
86
+ end
87
+
88
+ def self.add_formatter(name, file_path = nil)
89
+ formatters << [name, file_path]
90
+ end
91
+
92
+ def self.add_event_logger(logger)
93
+ event_handlers << logger
94
+ end
95
+
96
+ def self.apply_extra_config_options(extra_config_options)
97
+ if extra_config_options
98
+ extra_parsed_options = extra_config_options.inject({}) do |memo, option|
99
+ # Sanity check value.
100
+ if option.empty? || !option.include?("=")
101
+ raise UnparsableConfigOption, "Unparsable config option #{option.inspect}"
102
+ end
103
+ # Split including whitespace if someone does truly odd like
104
+ # --config-option "foo = bar"
105
+ key, value = option.split(/\s*=\s*/, 2)
106
+ # Call to_sym because Chef::Config expects only symbol keys. Also
107
+ # runs a simple parse on the string for some common types.
108
+ memo[key.to_sym] = YAML.safe_load(value)
109
+ memo
110
+ end
111
+ merge!(extra_parsed_options)
112
+ end
113
+ end
114
+
115
+ # Config file to load (client.rb, knife.rb, etc. defaults set differently in knife, chef-client, etc.)
116
+ configurable(:config_file)
117
+
118
+ default(:config_dir) do
119
+ if config_file
120
+ PathHelper.dirname(PathHelper.canonical_path(config_file, false))
121
+ else
122
+ PathHelper.join(user_home, ".chef", "")
123
+ end
124
+ end
125
+
126
+ default :formatters, []
127
+
128
+ def self.is_valid_url?(uri)
129
+ url = uri.to_s.strip
130
+ /^http:\/\// =~ url || /^https:\/\// =~ url || /^chefzero:/ =~ url
131
+ end
132
+ # Override the config dispatch to set the value of multiple server options simultaneously
133
+ #
134
+ # === Parameters
135
+ # url<String>:: String to be set for all of the chef-server-api URL's
136
+ #
137
+ configurable(:chef_server_url).writes_value do |uri|
138
+ unless is_valid_url? uri
139
+ raise ConfigurationError, "#{uri} is an invalid chef_server_url."
140
+ end
141
+ uri.to_s.strip
142
+ end
143
+
144
+ # When you are using ActiveSupport, they monkey-patch 'daemonize' into Kernel.
145
+ # So while this is basically identical to what method_missing would do, we pull
146
+ # it up here and get a real method written so that things get dispatched
147
+ # properly.
148
+ configurable(:daemonize).writes_value { |v| v }
149
+
150
+ # The root where all local chef object data is stored. cookbooks, data bags,
151
+ # environments are all assumed to be in separate directories under this.
152
+ # chef-solo uses these directories for input data. knife commands
153
+ # that upload or download files (such as knife upload, knife role from file,
154
+ # etc.) work.
155
+ default :chef_repo_path do
156
+ if configuration[:cookbook_path]
157
+ if configuration[:cookbook_path].kind_of?(String)
158
+ File.expand_path("..", configuration[:cookbook_path])
159
+ else
160
+ configuration[:cookbook_path].map do |path|
161
+ File.expand_path("..", path)
162
+ end
163
+ end
164
+ elsif configuration[:cookbook_artifact_path]
165
+ File.expand_path("..", configuration[:cookbook_artifact_path])
166
+ else
167
+ cache_path
168
+ end
169
+ end
170
+
171
+ def self.find_chef_repo_path(cwd)
172
+ # In local mode, we auto-discover the repo root by looking for a path with "cookbooks" under it.
173
+ # This allows us to run config-free.
174
+ path = cwd
175
+ until File.directory?(PathHelper.join(path, "cookbooks")) || File.directory?(PathHelper.join(path, "cookbook_artifacts"))
176
+ new_path = File.expand_path("..", path)
177
+ if new_path == path
178
+ ChefConfig.logger.warn("No cookbooks directory found at or above current directory. Assuming #{cwd}.")
179
+ return cwd
180
+ end
181
+ path = new_path
182
+ end
183
+ ChefConfig.logger.info("Auto-discovered chef repository at #{path}")
184
+ path
185
+ end
186
+
187
+ def self.derive_path_from_chef_repo_path(child_path)
188
+ if chef_repo_path.kind_of?(String)
189
+ PathHelper.join(chef_repo_path, child_path)
190
+ else
191
+ chef_repo_path.uniq.map { |path| PathHelper.join(path, child_path) }
192
+ end
193
+ end
194
+
195
+ # Location of acls on disk. String or array of strings.
196
+ # Defaults to <chef_repo_path>/acls.
197
+ default(:acl_path) { derive_path_from_chef_repo_path("acls") }
198
+
199
+ # Location of clients on disk. String or array of strings.
200
+ # Defaults to <chef_repo_path>/clients.
201
+ default(:client_path) { derive_path_from_chef_repo_path("clients") }
202
+
203
+ # Location of client keys on disk. String or array of strings.
204
+ # Defaults to <chef_repo_path>/client_keys.
205
+ default(:client_key_path) { derive_path_from_chef_repo_path("client_keys") }
206
+
207
+ # Location of containers on disk. String or array of strings.
208
+ # Defaults to <chef_repo_path>/containers.
209
+ default(:container_path) { derive_path_from_chef_repo_path("containers") }
210
+
211
+ # Location of cookbook_artifacts on disk. String or array of strings.
212
+ # Defaults to <chef_repo_path>/cookbook_artifacts.
213
+ default(:cookbook_artifact_path) { derive_path_from_chef_repo_path("cookbook_artifacts") }
214
+
215
+ # Location of cookbooks on disk. String or array of strings.
216
+ # Defaults to <chef_repo_path>/cookbooks. If chef_repo_path
217
+ # is not specified, this is set to [/var/chef/cookbooks, /var/chef/site-cookbooks]).
218
+ default(:cookbook_path) do
219
+ if configuration[:chef_repo_path]
220
+ derive_path_from_chef_repo_path("cookbooks")
221
+ else
222
+ Array(derive_path_from_chef_repo_path("cookbooks")).flatten +
223
+ Array(derive_path_from_chef_repo_path("site-cookbooks")).flatten
224
+ end
225
+ end
226
+
227
+ # Location of data bags on disk. String or array of strings.
228
+ # Defaults to <chef_repo_path>/data_bags.
229
+ default(:data_bag_path) { derive_path_from_chef_repo_path("data_bags") }
230
+
231
+ # Location of environments on disk. String or array of strings.
232
+ # Defaults to <chef_repo_path>/environments.
233
+ default(:environment_path) { derive_path_from_chef_repo_path("environments") }
234
+
235
+ # Location of groups on disk. String or array of strings.
236
+ # Defaults to <chef_repo_path>/groups.
237
+ default(:group_path) { derive_path_from_chef_repo_path("groups") }
238
+
239
+ # Location of nodes on disk. String or array of strings.
240
+ # Defaults to <chef_repo_path>/nodes.
241
+ default(:node_path) { derive_path_from_chef_repo_path("nodes") }
242
+
243
+ # Location of policies on disk. String or array of strings.
244
+ # Defaults to <chef_repo_path>/policies.
245
+ default(:policy_path) { derive_path_from_chef_repo_path("policies") }
246
+
247
+ # Location of policy_groups on disk. String or array of strings.
248
+ # Defaults to <chef_repo_path>/policy_groups.
249
+ default(:policy_group_path) { derive_path_from_chef_repo_path("policy_groups") }
250
+
251
+ # Location of roles on disk. String or array of strings.
252
+ # Defaults to <chef_repo_path>/roles.
253
+ default(:role_path) { derive_path_from_chef_repo_path("roles") }
254
+
255
+ # Location of users on disk. String or array of strings.
256
+ # Defaults to <chef_repo_path>/users.
257
+ default(:user_path) { derive_path_from_chef_repo_path("users") }
258
+
259
+ # Location of policies on disk. String or array of strings.
260
+ # Defaults to <chef_repo_path>/policies.
261
+ default(:policy_path) { derive_path_from_chef_repo_path("policies") }
262
+
263
+ # Turn on "path sanity" by default.
264
+ default :enforce_path_sanity, false
265
+
266
+ # Formatted Chef Client output is a beta feature, disabled by default:
267
+ default :formatter, "null"
268
+
269
+ # The number of times the client should retry when registering with the server
270
+ default :client_registration_retries, 5
271
+
272
+ # An array of paths to search for knife exec scripts if they aren't in the current directory
273
+ default :script_path, []
274
+
275
+ # The root of all caches (checksums, cache and backup). If local mode is on,
276
+ # this is under the user's home directory.
277
+ default(:cache_path) do
278
+ if local_mode
279
+ PathHelper.join(config_dir, "local-mode-cache")
280
+ else
281
+ primary_cache_root = platform_specific_path("/var")
282
+ primary_cache_path = platform_specific_path("/var/chef")
283
+ # Use /var/chef as the cache path only if that folder exists and we can read and write
284
+ # into it, or /var exists and we can read and write into it (we'll create /var/chef later).
285
+ # Otherwise, we'll create .chef under the user's home directory and use that as
286
+ # the cache path.
287
+ unless path_accessible?(primary_cache_path) || path_accessible?(primary_cache_root)
288
+ secondary_cache_path = PathHelper.join(user_home, ".chef")
289
+ ChefConfig.logger.info("Unable to access cache at #{primary_cache_path}. Switching cache to #{secondary_cache_path}")
290
+ secondary_cache_path
291
+ else
292
+ primary_cache_path
293
+ end
294
+ end
295
+ end
296
+
297
+ # Returns true only if the path exists and is readable and writeable for the user.
298
+ def self.path_accessible?(path)
299
+ File.exists?(path) && File.readable?(path) && File.writable?(path)
300
+ end
301
+
302
+ # Where cookbook files are stored on the server (by content checksum)
303
+ default(:checksum_path) { PathHelper.join(cache_path, "checksums") }
304
+
305
+ # Where chef's cache files should be stored
306
+ default(:file_cache_path) { PathHelper.join(cache_path, "cache") }
307
+
308
+ # Where backups of chef-managed files should go
309
+ default(:file_backup_path) { PathHelper.join(cache_path, "backup") }
310
+
311
+ # The chef-client (or solo) lockfile.
312
+ #
313
+ # If your `file_cache_path` resides on a NFS (or non-flock()-supporting
314
+ # fs), it's recommended to set this to something like
315
+ # '/tmp/chef-client-running.pid'
316
+ default(:lockfile) { PathHelper.join(file_cache_path, "chef-client-running.pid") }
317
+
318
+ ## Daemonization Settings ##
319
+ # What user should Chef run as?
320
+ default :user, nil
321
+ default :group, nil
322
+ default :umask, 0022
323
+
324
+ # Valid log_levels are:
325
+ # * :trace
326
+ # * :debug
327
+ # * :info
328
+ # * :warn
329
+ # * :fatal
330
+ # These work as you'd expect. There is also a special `:auto` setting.
331
+ # When set to :auto, Chef will auto adjust the log verbosity based on
332
+ # context. When a tty is available (usually because the user is running chef
333
+ # in a console), the log level is set to :warn, and output formatters are
334
+ # used as the primary mode of output. When a tty is not available, the
335
+ # logger is the primary mode of output, and the log level is set to :info
336
+ default :log_level, :auto
337
+
338
+ # Logging location as either an IO stream or string representing log file path
339
+ default :log_location, STDOUT
340
+
341
+ # Using `force_formatter` causes chef to default to formatter output when STDOUT is not a tty
342
+ default :force_formatter, false
343
+
344
+ # Using `force_logger` causes chef to default to logger output when STDOUT is a tty
345
+ default :force_logger, false
346
+
347
+ # Using 'stream_execute_output' will have Chef always stream the execute output
348
+ default :stream_execute_output, false
349
+
350
+ # Using `show_download_progress` will display the overall progress
351
+ # of a remote file download
352
+ default :show_download_progress, false
353
+ # How often to update the progress meter, in percent
354
+ default :download_progress_interval, 10
355
+
356
+ default :http_retry_count, 5
357
+ default :http_retry_delay, 5
358
+ # Whether or not to send the Authorization header again on http redirects.
359
+ # As per the plan in https://github.com/chef/chef/pull/7006, this will be
360
+ # False in Chef 14, True in Chef 15, and will be removed entirely in Chef 16.
361
+ default :http_disable_auth_on_redirect, false
362
+
363
+ default :interval, nil
364
+ default :once, nil
365
+ default :json_attribs, nil
366
+ # toggle info level log items that can create a lot of output
367
+ default :verbose_logging, true
368
+ default :node_name, nil
369
+ default :diff_disabled, false
370
+ default :diff_filesize_threshold, 10000000
371
+ default :diff_output_threshold, 1000000
372
+ default :local_mode, false
373
+
374
+ # Configures the mode of operation for ChefFS, which is applied to the
375
+ # ChefFS-based knife commands and chef-client's local mode. (ChefFS-based
376
+ # knife commands include: knife delete, knife deps, knife diff, knife down,
377
+ # knife edit, knife list, knife show, knife upload, and knife xargs.)
378
+ #
379
+ # Valid values are:
380
+ # * "static": ChefFS only manages objects that exist in a traditional Chef
381
+ # Repo as of Chef 11.
382
+ # * "everything": ChefFS manages all object types that existed on the OSS
383
+ # Chef 11 server.
384
+ # * "hosted_everything": ChefFS manages all object types as of the Chef 12
385
+ # Server, including RBAC objects and Policyfile objects (new to Chef 12).
386
+ default :repo_mode do
387
+ if local_mode && !chef_zero.osc_compat
388
+ "hosted_everything"
389
+ elsif chef_server_url =~ /\/+organizations\/.+/
390
+ "hosted_everything"
391
+ else
392
+ "everything"
393
+ end
394
+ end
395
+
396
+ default :pid_file, nil
397
+
398
+ # Whether Chef Zero local mode should bind to a port. All internal requests
399
+ # will go through the socketless code path regardless, so the socket is
400
+ # only needed if other processes will connect to the local mode server.
401
+ default :listen, false
402
+
403
+ config_context :chef_zero do
404
+ config_strict_mode true
405
+ default(:enabled) { ChefConfig::Config.local_mode }
406
+ default :host, "localhost"
407
+ default :port, 8889.upto(9999) # Will try ports from 8889-9999 until one works
408
+
409
+ # When set to a String, Chef Zero disables multitenant support. This is
410
+ # what you want when using Chef Zero to serve a single Chef Repo. Setting
411
+ # this to `false` enables multi-tenant.
412
+ default :single_org, "chef"
413
+
414
+ # Whether Chef Zero should operate in a mode analogous to OSS Chef Server
415
+ # 11 (true) or Chef Server 12 (false). Chef Zero can still serve
416
+ # policyfile objects in Chef 11 mode, as long as `repo_mode` is set to
417
+ # "hosted_everything". The primary differences are:
418
+ # * Chef 11 mode doesn't support multi-tennant, so there is no
419
+ # distinction between global and org-specific objects (since there are
420
+ # no orgs).
421
+ # * Chef 11 mode doesn't expose RBAC objects
422
+ default :osc_compat, false
423
+ end
424
+ default :chef_server_url, "https://localhost:443"
425
+
426
+ default(:chef_server_root) do
427
+ # if the chef_server_url is a path to an organization, aka
428
+ # 'some_url.../organizations/*' then remove the '/organization/*' by default
429
+ if configuration[:chef_server_url] =~ /\/organizations\/\S*$/
430
+ configuration[:chef_server_url].split("/")[0..-3].join("/")
431
+ elsif configuration[:chef_server_url] # default to whatever chef_server_url is
432
+ configuration[:chef_server_url]
433
+ else
434
+ "https://localhost:443"
435
+ end
436
+ end
437
+
438
+ default :rest_timeout, 300
439
+ default :yum_timeout, 900
440
+ default :yum_lock_timeout, 30
441
+ default :solo, false
442
+
443
+ # Are we running in old Chef Solo legacy mode?
444
+ default :solo_legacy_mode, false
445
+
446
+ default :splay, nil
447
+ default :why_run, false
448
+ default :color, false
449
+ default :client_fork, nil
450
+ default :ez, false
451
+ default :enable_reporting, true
452
+ default :enable_reporting_url_fatals, false
453
+ # Possible values for :audit_mode
454
+ # :enabled, :disabled, :audit_only,
455
+ #
456
+ # TODO: 11 Dec 2014: Currently audit-mode is an experimental feature
457
+ # and is disabled by default. When users choose to enable audit-mode,
458
+ # a warning is issued in application/client#reconfigure.
459
+ # This can be removed when audit-mode is enabled by default.
460
+ default :audit_mode, :disabled
461
+
462
+ # Chef only needs ohai to run the hostname plugin for the most basic
463
+ # functionality. If the rest of the ohai plugins are not needed (like in
464
+ # most of our testing scenarios)
465
+ default :minimal_ohai, false
466
+
467
+ # When consuming Ohai plugins from cookbook segments, we place those plugins in this directory.
468
+ # Subsequent chef client runs will wipe and re-populate the directory to ensure cleanliness
469
+ default(:ohai_segment_plugin_path) { PathHelper.join(config_dir, "ohai", "cookbook_plugins") }
470
+
471
+ ###
472
+ # Policyfile Settings
473
+ #
474
+ # Policyfile is a feature where a node gets its run list and cookbook
475
+ # version set from a single document on the server instead of expanding the
476
+ # run list and having the server compute the cookbook version set based on
477
+ # environment constraints.
478
+ #
479
+ # Policyfiles are auto-versioned. The user groups nodes by `policy_name`,
480
+ # which generally describes a hosts's functional role, and `policy_group`,
481
+ # which generally groups nodes by deployment phase (a.k.a., "environment").
482
+ # The Chef Server maps a given set of `policy_name` plus `policy_group` to
483
+ # a particular revision of a policy.
484
+
485
+ default :policy_name, nil
486
+ default :policy_group, nil
487
+
488
+ # Policyfiles can have multiple run lists, via the named run list feature.
489
+ # Generally this will be set by a CLI option via Chef::Application::Client,
490
+ # but it could be set in client.rb if desired.
491
+
492
+ default :named_run_list, nil
493
+
494
+ # During initial development, users were required to set `use_policyfile true`
495
+ # in `client.rb` to opt-in to policyfile use. Chef Client now examines
496
+ # configuration, node json, and the stored node to determine if policyfile
497
+ # usage is desired. This flag is still honored if set, but is unnecessary.
498
+ default :use_policyfile, false
499
+
500
+ # Policyfiles can be used in a native mode (default) or compatibility mode.
501
+ # Native mode requires Chef Server 12.1 (it can be enabled via feature flag
502
+ # on some prior versions). In native mode, policies and associated
503
+ # cookbooks are accessed via feature-specific APIs. In compat mode,
504
+ # policies are stored as data bags and cookbooks are stored at the
505
+ # cookbooks/ endpoint. Compatibility mode can be dangerous on existing Chef
506
+ # Servers; it's recommended to upgrade your Chef Server rather than use
507
+ # compatibility mode. Compatibility mode remains available so you can use
508
+ # policyfiles with servers that don't yet support the native endpoints.
509
+ default :policy_document_native_api, true
510
+
511
+ # When policyfiles are used in compatibility mode, `policy_name` and
512
+ # `policy_group` are instead specified using a combined configuration
513
+ # setting, `deployment_group`. For example, if policy_name should be
514
+ # "webserver" and policy_group should be "staging", then `deployment_group`
515
+ # should be set to "webserver-staging", which is the name of the data bag
516
+ # item that the policy will be stored as. NOTE: this setting only has an
517
+ # effect if `policy_document_native_api` is set to `false`.
518
+ default :deployment_group, nil
519
+
520
+ # Set these to enable SSL authentication / mutual-authentication
521
+ # with the server
522
+
523
+ # Client side SSL cert/key for mutual auth
524
+ default :ssl_client_cert, nil
525
+ default :ssl_client_key, nil
526
+
527
+ # Whether or not to verify the SSL cert for all HTTPS requests. When set to
528
+ # :verify_peer (default), all HTTPS requests will be validated regardless of other
529
+ # SSL verification settings. When set to :verify_none no HTTPS requests will
530
+ # be validated.
531
+ default :ssl_verify_mode, :verify_peer
532
+
533
+ # Whether or not to verify the SSL cert for HTTPS requests to the Chef
534
+ # server API. If set to `true`, the server's cert will be validated
535
+ # regardless of the :ssl_verify_mode setting. This is set to `true` when
536
+ # running in local-mode.
537
+ # NOTE: This is a workaround until verify_peer is enabled by default.
538
+ default(:verify_api_cert) { ChefConfig::Config.local_mode }
539
+
540
+ # Path to the default CA bundle files.
541
+ default :ssl_ca_path, nil
542
+ default(:ssl_ca_file) do
543
+ if ChefConfig.windows? && embedded_dir
544
+ cacert_path = File.join(embedded_dir, "ssl/certs/cacert.pem")
545
+ cacert_path if File.exist?(cacert_path)
546
+ else
547
+ nil
548
+ end
549
+ end
550
+
551
+ # A directory that contains additional SSL certificates to trust. Any
552
+ # certificates in this directory will be added to whatever CA bundle ruby
553
+ # is using. Use this to add self-signed certs for your Chef Server or local
554
+ # HTTP file servers.
555
+ default(:trusted_certs_dir) { PathHelper.join(config_dir, "trusted_certs") }
556
+
557
+ # A directory that contains additional configuration scripts to load for chef-client
558
+ default(:client_d_dir) { PathHelper.join(config_dir, "client.d") }
559
+
560
+ # A directory that contains additional configuration scripts to load for solo
561
+ default(:solo_d_dir) { PathHelper.join(config_dir, "solo.d") }
562
+
563
+ # A directory that contains additional configuration scripts to load for
564
+ # the workstation config
565
+ default(:config_d_dir) { PathHelper.join(config_dir, "config.d") }
566
+
567
+ # Where should chef-solo download recipes from?
568
+ default :recipe_url, nil
569
+
570
+ # Set to true if Chef is to set OpenSSL to run in FIPS mode
571
+ default(:fips) do
572
+ # CHEF_FIPS is used in testing to override checking for system level
573
+ # enablement. There are 3 possible values that this variable may have:
574
+ # nil - no override and the system will be checked
575
+ # empty - FIPS is NOT enabled
576
+ # a non empty value - FIPS is enabled
577
+ if ENV["CHEF_FIPS"] == ""
578
+ false
579
+ else
580
+ !ENV["CHEF_FIPS"].nil? || ChefConfig.fips?
581
+ end
582
+ end
583
+
584
+ # Initialize openssl
585
+ def self.init_openssl
586
+ if fips
587
+ enable_fips_mode
588
+ end
589
+ end
590
+
591
+ # Sets the version of the signed header authentication protocol to use (see
592
+ # the 'mixlib-authorization' project for more detail). Currently, versions
593
+ # 1.0, 1.1, and 1.3 are available.
594
+ default :authentication_protocol_version do
595
+ if fips
596
+ "1.3"
597
+ else
598
+ "1.1"
599
+ end
600
+ end
601
+
602
+ # This key will be used to sign requests to the Chef server. This location
603
+ # must be writable by Chef during initial setup when generating a client
604
+ # identity on the server.
605
+ #
606
+ # The chef-server will look up the public key for the client using the
607
+ # `node_name` of the client.
608
+ #
609
+ # If chef-zero is enabled, this defaults to nil (no authentication).
610
+ default(:client_key) { chef_zero.enabled ? nil : platform_specific_path("/etc/chef/client.pem") }
611
+
612
+ # A credentials file may contain a complete client key, rather than the path
613
+ # to one.
614
+ #
615
+ # We'll use this preferentially.
616
+ default :client_key_contents, nil
617
+
618
+ # When registering the client, should we allow the client key location to
619
+ # be a symlink? eg: /etc/chef/client.pem -> /etc/chef/prod-client.pem
620
+ # If the path of the key goes through a directory like /tmp this should
621
+ # never be set to true or its possibly an easily exploitable security hole.
622
+ default :follow_client_key_symlink, false
623
+
624
+ # This secret is used to decrypt encrypted data bag items.
625
+ default(:encrypted_data_bag_secret) do
626
+ if File.exist?(platform_specific_path("/etc/chef/encrypted_data_bag_secret"))
627
+ platform_specific_path("/etc/chef/encrypted_data_bag_secret")
628
+ else
629
+ nil
630
+ end
631
+ end
632
+
633
+ # As of Chef 13.0, version "3" is the default encrypted data bag item
634
+ # format.
635
+ #
636
+ default :data_bag_encrypt_version, 3
637
+
638
+ # When reading data bag items, any supported version is accepted. However,
639
+ # if all encrypted data bags have been generated with the version 2 format,
640
+ # it is recommended to disable support for earlier formats to improve
641
+ # security. For example, the version 2 format is identical to version 1
642
+ # except for the addition of an HMAC, so an attacker with MITM capability
643
+ # could downgrade an encrypted data bag to version 1 as part of an attack.
644
+ default :data_bag_decrypt_minimum_version, 0
645
+
646
+ # If there is no file in the location given by `client_key`, chef-client
647
+ # will temporarily use the "validator" identity to generate one. If the
648
+ # `client_key` is not present and the `validation_key` is also not present,
649
+ # chef-client will not be able to authenticate to the server.
650
+ #
651
+ # The `validation_key` is never used if the `client_key` exists.
652
+ #
653
+ # If chef-zero is enabled, this defaults to nil (no authentication).
654
+ default(:validation_key) { chef_zero.enabled ? nil : platform_specific_path("/etc/chef/validation.pem") }
655
+ default :validation_client_name, "chef-validator"
656
+
657
+ default :validation_key_contents, nil
658
+ # When creating a new client via the validation_client account, Chef 11
659
+ # servers allow the client to generate a key pair locally and send the
660
+ # public key to the server. This is more secure and helps offload work from
661
+ # the server, enhancing scalability. If enabled and the remote server
662
+ # implements only the Chef 10 API, client registration will not work
663
+ # properly.
664
+ #
665
+ # The default value is `true`. Set to `false` to disable client-side key
666
+ # generation (server generates client keys).
667
+ default(:local_key_generation) { true }
668
+
669
+ # Zypper package provider gpg checks. Set to false to disable package
670
+ # gpg signature checking globally. This will warn you that it is a
671
+ # bad thing to do.
672
+ default :zypper_check_gpg, true
673
+
674
+ # Report Handlers
675
+ default :report_handlers, []
676
+
677
+ # Event Handlers
678
+ default :event_handlers, []
679
+
680
+ default :disable_event_loggers, false
681
+
682
+ # Exception Handlers
683
+ default :exception_handlers, []
684
+
685
+ # Start handlers
686
+ default :start_handlers, []
687
+
688
+ # Syntax Check Cache. Knife keeps track of files that is has already syntax
689
+ # checked by storing files in this directory. `syntax_check_cache_path` is
690
+ # the new (and preferred) configuration setting. If not set, knife will
691
+ # fall back to using cache_options[:path], which is deprecated but exists in
692
+ # many client configs generated by pre-Chef-11 bootstrappers.
693
+ default(:syntax_check_cache_path) { cache_options[:path] }
694
+
695
+ # Deprecated:
696
+ # Move this to the default value of syntax_cache_path when this is removed.
697
+ default(:cache_options) { { :path => PathHelper.join(config_dir, "syntaxcache") } }
698
+
699
+ # Whether errors should be raised for deprecation warnings. When set to
700
+ # `false` (the default setting), a warning is emitted but code using
701
+ # deprecated methods/features/etc. should work normally otherwise. When set
702
+ # to `true`, usage of deprecated methods/features will raise a
703
+ # `DeprecatedFeatureError`. This is used by Chef's tests to ensure that
704
+ # deprecated functionality is not used internally by Chef. End users
705
+ # should generally leave this at the default setting (especially in
706
+ # production), but it may be useful when testing cookbooks or other code if
707
+ # the user wishes to aggressively address deprecations.
708
+ default(:treat_deprecation_warnings_as_errors) do
709
+ # Using an environment variable allows this setting to be inherited in
710
+ # tests that spawn new processes.
711
+ ENV.key?("CHEF_TREAT_DEPRECATION_WARNINGS_AS_ERRORS")
712
+ end
713
+
714
+ # Whether the resource count should be updated for log resource
715
+ # on running chef-client
716
+ default :count_log_resource_updates, true
717
+
718
+ # The selected profile when using credentials.
719
+ default :profile, nil
720
+
721
+ default :chef_guid_path do
722
+ PathHelper.join(config_dir, "chef_guid")
723
+ end
724
+
725
+ default :chef_guid, nil
726
+
727
+ # knife configuration data
728
+ config_context :knife do
729
+ # XXX: none of these default values are applied to knife (and would create a backcompat
730
+ # break in knife if this bug was fixed since many of the defaults below are wrong). this appears
731
+ # to be the start of an attempt to be able to use config_strict_mode true? if so, this approach
732
+ # is fraught with peril because this namespace is used by every knife plugin in the wild and
733
+ # we would need to validate every cli option in every knife attribute out there and list them all here.
734
+ #
735
+ # based on the way that people may define `knife[:foobar] = "something"` for the knife-foobar
736
+ # gem plugin i'm pretty certain we can never turn on anything like config_string_mode since
737
+ # any config value may be a typo or it may be in some gem in some knife plugin we don't know about.
738
+ #
739
+ # we do still need to maintain at least one of these so that the knife config hash gets
740
+ # created.
741
+ #
742
+ # this whole situation is deeply unsatisfying.
743
+ default :ssh_port, nil
744
+ default :ssh_user, nil
745
+ default :ssh_attribute, nil
746
+ default :ssh_gateway, nil
747
+ default :ssh_gateway_identity, nil
748
+ default :bootstrap_version, nil
749
+ default :bootstrap_proxy, nil
750
+ default :bootstrap_template, nil
751
+ default :secret, nil
752
+ default :secret_file, nil
753
+ default :identity_file, nil
754
+ default :host_key_verify, nil
755
+ default :forward_agent, nil
756
+ default :sort_status_reverse, nil
757
+ default :hints, {}
758
+ end
759
+
760
+ def self.set_defaults_for_windows
761
+ # Those lists of regular expressions define what chef considers a
762
+ # valid user and group name
763
+ # From http://technet.microsoft.com/en-us/library/cc776019(WS.10).aspx
764
+ principal_valid_regex_part = '[^"\/\\\\\[\]\:;|=,+*?<>]+'
765
+ default :user_valid_regex, [ /^(#{principal_valid_regex_part}\\)?#{principal_valid_regex_part}$/ ]
766
+ default :group_valid_regex, [ /^(#{principal_valid_regex_part}\\)?#{principal_valid_regex_part}$/ ]
767
+
768
+ default :fatal_windows_admin_check, false
769
+ end
770
+
771
+ def self.set_defaults_for_nix
772
+ # Those lists of regular expressions define what chef considers a
773
+ # valid user and group name
774
+ #
775
+ # user/group cannot start with '-', '+' or '~'
776
+ # user/group cannot contain ':', ',' or non-space-whitespace or null byte
777
+ # everything else is allowed (UTF-8, spaces, etc) and we delegate to your O/S useradd program to barf or not
778
+ # copies: http://anonscm.debian.org/viewvc/pkg-shadow/debian/trunk/debian/patches/506_relaxed_usernames?view=markup
779
+ default :user_valid_regex, [ /^[^-+~:,\t\r\n\f\0]+[^:,\t\r\n\f\0]*$/ ]
780
+ default :group_valid_regex, [ /^[^-+~:,\t\r\n\f\0]+[^:,\t\r\n\f\0]*$/ ]
781
+ end
782
+
783
+ # Those lists of regular expressions define what chef considers a
784
+ # valid user and group name
785
+ if ChefConfig.windows?
786
+ set_defaults_for_windows
787
+ else
788
+ set_defaults_for_nix
789
+ end
790
+
791
+ # This provides a hook which rspec can stub so that we can avoid twiddling
792
+ # global state in tests.
793
+ def self.env
794
+ ENV
795
+ end
796
+
797
+ def self.windows_home_path
798
+ ChefConfig.logger.deprecation("Chef::Config.windows_home_path is now deprecated. Consider using Chef::Util::PathHelper.home instead.")
799
+ PathHelper.home
800
+ end
801
+
802
+ # returns a platform specific path to the user home dir if set, otherwise default to current directory.
803
+ default( :user_home ) { PathHelper.home || Dir.pwd }
804
+
805
+ # Enable file permission fixup for selinux. Fixup will be done
806
+ # only if selinux is enabled in the system.
807
+ default :enable_selinux_file_permission_fixup, true
808
+
809
+ # Use atomic updates (i.e. move operation) while updating contents
810
+ # of the files resources. When set to false copy operation is
811
+ # used to update files.
812
+ #
813
+ # NOTE: CHANGING THIS SETTING MAY CAUSE CORRUPTION, DATA LOSS AND
814
+ # INSTABILITY.
815
+ default :file_atomic_update, true
816
+
817
+ # There are 3 possible values for this configuration setting.
818
+ # true => file staging is done in the destination directory
819
+ # false => file staging is done via tempfiles under ENV['TMP']
820
+ # :auto => file staging will try using destination directory if possible and
821
+ # will fall back to ENV['TMP'] if destination directory is not usable.
822
+ default :file_staging_uses_destdir, :auto
823
+
824
+ # Exit if another run is in progress and the chef-client is unable to
825
+ # get the lock before time expires. If nil, no timeout is enforced. (Exits
826
+ # immediately if 0.)
827
+ default :run_lock_timeout, nil
828
+
829
+ # Number of worker threads for syncing cookbooks in parallel. Increasing
830
+ # this number can result in gateway errors from the server (namely 503 and 504).
831
+ # If you are seeing this behavior while using the default setting, reducing
832
+ # the number of threads will help.
833
+ default :cookbook_sync_threads, 10
834
+
835
+ # At the beginning of the Chef Client run, the cookbook manifests are downloaded which
836
+ # contain URLs for every file in every relevant cookbook. Most of the files
837
+ # (recipes, resources, providers, libraries, etc) are immediately synchronized
838
+ # at the start of the run. The handling of "files" and "templates" directories,
839
+ # however, have two modes of operation. They can either all be downloaded immediately
840
+ # at the start of the run (no_lazy_load==true) or else they can be lazily loaded as
841
+ # cookbook_file or template resources are converged which require them (no_lazy_load==false).
842
+ #
843
+ # The advantage of lazily loading these files is that unnecessary files are not
844
+ # synchronized. This may be useful to users with large files checked into cookbooks which
845
+ # are only selectively downloaded to a subset of clients which use the cookbook. However,
846
+ # better solutions are to either isolate large files into individual cookbooks and only
847
+ # include those cookbooks in the run lists of the servers that need them -- or move to
848
+ # using remote_file and a more appropriate backing store like S3 for large file
849
+ # distribution.
850
+ #
851
+ # The disadvantages of lazily loading files are that users some time find it
852
+ # confusing that their cookbooks are not fully synchronzied to the cache initially,
853
+ # and more importantly the time-sensitive URLs which are in the manifest may time
854
+ # out on long Chef runs before the resource that uses the file is converged
855
+ # (leading to many confusing 403 errors on template/cookbook_file resources).
856
+ #
857
+ default :no_lazy_load, true
858
+
859
+ # A whitelisted array of attributes you want sent over the wire when node
860
+ # data is saved.
861
+ # The default setting is nil, which collects all data. Setting to [] will not
862
+ # collect any data for save.
863
+ default :automatic_attribute_whitelist, nil
864
+ default :default_attribute_whitelist, nil
865
+ default :normal_attribute_whitelist, nil
866
+ default :override_attribute_whitelist, nil
867
+
868
+ # A blacklisted array of attributes you do not want to send over the
869
+ # wire when node data is saved
870
+ # The default setting is nil, which collects all data. Setting to [] will
871
+ # still collect all data for save
872
+ default :automatic_attribute_blacklist, nil
873
+ default :default_attribute_blacklist, nil
874
+ default :normal_attribute_blacklist, nil
875
+ default :override_attribute_blacklist, nil
876
+
877
+ # Pull down all the rubygems versions from rubygems and cache them the first time we do a gem_package or
878
+ # chef_gem install. This is memory-expensive and will grow without bounds, but will reduce network
879
+ # round trips.
880
+ default :rubygems_cache_enabled, false
881
+
882
+ config_context :windows_service do
883
+ # Set `watchdog_timeout` to the number of seconds to wait for a chef-client run
884
+ # to finish
885
+ default :watchdog_timeout, 2 * (60 * 60) # 2 hours
886
+ end
887
+
888
+ # Add an empty and non-strict config_context for chefdk. This lets the user
889
+ # have code like `chefdk.generator_cookbook "/path/to/cookbook"` in their
890
+ # config.rb, and it will be ignored by tools like knife and ohai. ChefDK
891
+ # itself can define the config options it accepts and enable strict mode,
892
+ # and that will only apply when running `chef` commands.
893
+ config_context :chefdk do
894
+ end
895
+
896
+ # Configuration options for Data Collector reporting. These settings allow
897
+ # the user to configure where to send their Data Collector data, what token
898
+ # to send, and whether Data Collector should report its findings in client
899
+ # mode vs. solo mode.
900
+ config_context :data_collector do
901
+ # Full URL to the endpoint that will receive our data. If nil, the
902
+ # data collector will not run.
903
+ # Ex: http://my-data-collector.mycompany.com/ingest
904
+ default(:server_url) do
905
+ if config_parent.solo || config_parent.local_mode
906
+ nil
907
+ else
908
+ File.join(config_parent.chef_server_url, "/data-collector")
909
+ end
910
+ end
911
+
912
+ # An optional pre-shared token to pass as an HTTP header (x-data-collector-token)
913
+ # that can be used to determine whether or not the poster of this
914
+ # run data should be trusted.
915
+ # Ex: some-uuid-here
916
+ default :token, nil
917
+
918
+ # The Chef mode during which Data Collector is allowed to function. This
919
+ # can be used to run Data Collector only when running as Chef Solo but
920
+ # not when using Chef Client.
921
+ # Options: :solo (for both Solo Legacy Mode and Client Local Mode), :client, :both
922
+ default :mode, :both
923
+
924
+ # When the Data Collector cannot send the "starting a run" message to
925
+ # the Data Collector server, the Data Collector will be disabled for that
926
+ # run. In some situations, such as highly-regulated environments, it
927
+ # may be more reasonable to prevent Chef from performing the actual run.
928
+ # In these situations, setting this value to true will cause the Chef
929
+ # run to raise an exception before starting any converge activities.
930
+ default :raise_on_failure, false
931
+
932
+ # A user-supplied Organization string that can be sent in payloads
933
+ # generated by the DataCollector when Chef is run in Solo mode. This
934
+ # allows users to associate their Solo nodes with faux organizations
935
+ # without the nodes being connected to an actual Chef Server.
936
+ default :organization, nil
937
+ end
938
+
939
+ configurable(:http_proxy)
940
+ configurable(:http_proxy_user)
941
+ configurable(:http_proxy_pass)
942
+ configurable(:https_proxy)
943
+ configurable(:https_proxy_user)
944
+ configurable(:https_proxy_pass)
945
+ configurable(:ftp_proxy)
946
+ configurable(:ftp_proxy_user)
947
+ configurable(:ftp_proxy_pass)
948
+ configurable(:no_proxy)
949
+
950
+ # Public method that users should call to export proxies to the appropriate
951
+ # environment variables. This method should be called after the config file is
952
+ # parsed and loaded.
953
+ # TODO add some post-file-parsing logic that automatically calls this so
954
+ # users don't have to
955
+ def self.export_proxies
956
+ export_proxy("http", http_proxy, http_proxy_user, http_proxy_pass) if http_proxy
957
+ export_proxy("https", https_proxy, https_proxy_user, https_proxy_pass) if https_proxy
958
+ export_proxy("ftp", ftp_proxy, ftp_proxy_user, ftp_proxy_pass) if ftp_proxy
959
+ export_no_proxy(no_proxy) if no_proxy
960
+ end
961
+
962
+ # Character classes for Addressable
963
+ # See https://www.ietf.org/rfc/rfc3986.txt 3.2.1
964
+ # The user part may not have a : in it
965
+ USER = Addressable::URI::CharacterClasses::UNRESERVED + Addressable::URI::CharacterClasses::SUB_DELIMS
966
+ # The password part may have any valid USERINFO characters
967
+ PASSWORD = USER + "\\:"
968
+
969
+ # Builds a proxy uri and exports it to the appropriate environment variables. Examples:
970
+ # http://username:password@hostname:port
971
+ # https://username@hostname:port
972
+ # ftp://hostname:port
973
+ # when
974
+ # scheme = "http", "https", or "ftp"
975
+ # hostport = hostname:port or scheme://hostname:port
976
+ # user = username
977
+ # pass = password
978
+ # @api private
979
+ def self.export_proxy(scheme, path, user, pass)
980
+ path = "#{scheme}://#{path}" unless path.include?("://")
981
+ # URI.split returns the following parts:
982
+ # [scheme, userinfo, host, port, registry, path, opaque, query, fragment]
983
+ uri = Addressable::URI.encode(path, Addressable::URI)
984
+
985
+ if user && !user.empty?
986
+ userinfo = Addressable::URI.encode_component(user, USER)
987
+ if pass
988
+ userinfo << ":#{Addressable::URI.encode_component(pass, PASSWORD)}"
989
+ end
990
+ uri.userinfo = userinfo
991
+ end
992
+
993
+ path = uri.to_s
994
+ ENV["#{scheme}_proxy".downcase] = path unless ENV["#{scheme}_proxy".downcase]
995
+ ENV["#{scheme}_proxy".upcase] = path unless ENV["#{scheme}_proxy".upcase]
996
+ end
997
+
998
+ # @api private
999
+ def self.export_no_proxy(value)
1000
+ ENV["no_proxy"] = value unless ENV["no_proxy"]
1001
+ ENV["NO_PROXY"] = value unless ENV["NO_PROXY"]
1002
+ end
1003
+
1004
+ # Given a scheme, host, and port, return the correct proxy URI based on the
1005
+ # set environment variables, unless exluded by no_proxy, in which case nil
1006
+ # is returned
1007
+ def self.proxy_uri(scheme, host, port)
1008
+ proxy_env_var = ENV["#{scheme}_proxy"].to_s.strip
1009
+
1010
+ # Check if the proxy string contains a scheme. If not, add the url's scheme to the
1011
+ # proxy before parsing. The regex /^.*:\/\// matches, for example, http://. Reusing proxy
1012
+ # here since we are really just trying to get the string built correctly.
1013
+ proxy = if !proxy_env_var.empty?
1014
+ if proxy_env_var =~ /^.*:\/\//
1015
+ URI.parse(proxy_env_var)
1016
+ else
1017
+ URI.parse("#{scheme}://#{proxy_env_var}")
1018
+ end
1019
+ end
1020
+
1021
+ return proxy unless fuzzy_hostname_match_any?(host, ENV["no_proxy"])
1022
+ end
1023
+
1024
+ # Chef requires an English-language UTF-8 locale to function properly. We attempt
1025
+ # to use the 'locale -a' command and search through a list of preferences until we
1026
+ # find one that we can use. On Ubuntu systems we should find 'C.UTF-8' and be
1027
+ # able to use that even if there is no English locale on the server, but Mac, Solaris,
1028
+ # AIX, etc do not have that locale. We then try to find an English locale and fall
1029
+ # back to 'C' if we do not. The choice of fallback is pick-your-poison. If we try
1030
+ # to do the work to return a non-US UTF-8 locale then we fail inside of providers when
1031
+ # things like 'svn info' return Japanese and we can't parse them. OTOH, if we pick 'C' then
1032
+ # we will blow up on UTF-8 characters. Between the warn we throw and the Encoding
1033
+ # exception that ruby will throw it is more obvious what is broken if we drop UTF-8 by
1034
+ # default rather than drop English.
1035
+ #
1036
+ # If there is no 'locale -a' then we return 'en_US.UTF-8' since that is the most commonly
1037
+ # available English UTF-8 locale. However, all modern POSIXen should support 'locale -a'.
1038
+ def self.guess_internal_locale
1039
+ # https://github.com/chef/chef/issues/2181
1040
+ # Some systems have the `locale -a` command, but the result has
1041
+ # invalid characters for the default encoding.
1042
+ #
1043
+ # For example, on CentOS 6 with ENV['LANG'] = "en_US.UTF-8",
1044
+ # `locale -a`.split fails with ArgumentError invalid UTF-8 encoding.
1045
+ cmd = Mixlib::ShellOut.new("locale -a").run_command
1046
+ cmd.error!
1047
+ locales = cmd.stdout.split
1048
+ case
1049
+ when locales.include?("C.UTF-8")
1050
+ "C.UTF-8"
1051
+ when locales.include?("en_US.UTF-8"), locales.include?("en_US.utf8")
1052
+ "en_US.UTF-8"
1053
+ when locales.include?("en.UTF-8")
1054
+ "en.UTF-8"
1055
+ else
1056
+ # Will match en_ZZ.UTF-8, en_ZZ.utf-8, en_ZZ.UTF8, en_ZZ.utf8
1057
+ guesses = locales.select { |l| l =~ /^en_.*UTF-?8$/i }
1058
+ unless guesses.empty?
1059
+ guessed_locale = guesses.first
1060
+ # Transform into the form en_ZZ.UTF-8
1061
+ guessed_locale.gsub(/UTF-?8$/i, "UTF-8")
1062
+ else
1063
+ ChefConfig.logger.warn "Please install an English UTF-8 locale for Chef to use, falling back to C locale and disabling UTF-8 support."
1064
+ "C"
1065
+ end
1066
+ end
1067
+ rescue
1068
+ if ChefConfig.windows?
1069
+ ChefConfig.logger.trace "Defaulting to locale en_US.UTF-8 on Windows, until it matters that we do something else."
1070
+ else
1071
+ ChefConfig.logger.trace "No usable locale -a command found, assuming you have en_US.UTF-8 installed."
1072
+ end
1073
+ "en_US.UTF-8"
1074
+ end
1075
+
1076
+ default :internal_locale, guess_internal_locale
1077
+
1078
+ # Force UTF-8 Encoding, for when we fire up in the 'C' locale or other strange locales (e.g.
1079
+ # japanese windows encodings). If we do not do this, then knife upload will fail when a cookbook's
1080
+ # README.md has UTF-8 characters that do not encode in whatever surrounding encoding we have been
1081
+ # passed. Effectively, the Chef Ecosystem is globally UTF-8 by default. Anyone who wants to be
1082
+ # able to upload Shift_JIS or ISO-8859-1 files needs to mark *those* files explicitly with
1083
+ # magic tags to make ruby correctly identify the encoding being used. Changing this default will
1084
+ # break Chef community cookbooks and is very highly discouraged.
1085
+ default :ruby_encoding, Encoding::UTF_8
1086
+
1087
+ # can be set to a string or array of strings for URIs to set as rubygems sources
1088
+ default :rubygems_url, "https://www.rubygems.org"
1089
+
1090
+ # If installed via an omnibus installer, this gives the path to the
1091
+ # "embedded" directory which contains all of the software packaged with
1092
+ # omnibus. This is used to locate the cacert.pem file on windows.
1093
+ def self.embedded_dir
1094
+ Pathname.new(_this_file).ascend do |path|
1095
+ if path.basename.to_s == "embedded"
1096
+ return path.to_s
1097
+ end
1098
+ end
1099
+
1100
+ nil
1101
+ end
1102
+
1103
+ # Path to this file in the current install.
1104
+ def self._this_file
1105
+ File.expand_path(__FILE__)
1106
+ end
1107
+
1108
+ # Set fips mode in openssl. Do any patching necessary to make
1109
+ # sure Chef runs do not crash.
1110
+ # @api private
1111
+ def self.enable_fips_mode
1112
+ OpenSSL.fips_mode = true
1113
+ require "digest"
1114
+ require "digest/sha1"
1115
+ require "digest/md5"
1116
+ # Remove pre-existing constants if they do exist to reduce the
1117
+ # amount of log spam and warnings.
1118
+ Digest.send(:remove_const, "SHA1") if Digest.const_defined?("SHA1")
1119
+ Digest.const_set("SHA1", OpenSSL::Digest::SHA1)
1120
+ OpenSSL::Digest.send(:remove_const, "MD5") if OpenSSL::Digest.const_defined?("MD5")
1121
+ OpenSSL::Digest.const_set("MD5", Digest::MD5)
1122
+ ChefConfig.logger.debug "FIPS mode is enabled."
1123
+ end
1124
+ end
1125
+ end