chef-config 12.8.1 → 12.9.38

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