chef-config 13.8.0 → 13.8.3

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