knife-windows 0.8.2 → 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (47) hide show
  1. checksums.yaml +5 -13
  2. data/.gitignore +1 -0
  3. data/.travis.yml +16 -2
  4. data/CHANGELOG.md +38 -4
  5. data/DOC_CHANGES.md +331 -15
  6. data/Gemfile +2 -1
  7. data/README.md +306 -71
  8. data/RELEASE_NOTES.md +63 -43
  9. data/Rakefile +9 -4
  10. data/appveyor.yml +42 -0
  11. data/ci.gemfile +15 -0
  12. data/knife-windows.gemspec +6 -4
  13. data/lib/chef/knife/bootstrap/windows-chef-client-msi.erb +96 -71
  14. data/lib/chef/knife/bootstrap_windows_base.rb +219 -37
  15. data/lib/chef/knife/bootstrap_windows_ssh.rb +22 -5
  16. data/lib/chef/knife/bootstrap_windows_winrm.rb +24 -24
  17. data/lib/chef/knife/core/windows_bootstrap_context.rb +146 -12
  18. data/lib/chef/knife/knife_windows_base.rb +33 -0
  19. data/lib/chef/knife/windows_cert_generate.rb +155 -0
  20. data/lib/chef/knife/windows_cert_install.rb +68 -0
  21. data/lib/chef/knife/windows_helper.rb +3 -1
  22. data/lib/chef/knife/windows_listener_create.rb +107 -0
  23. data/lib/chef/knife/winrm.rb +103 -206
  24. data/lib/chef/knife/winrm_base.rb +30 -11
  25. data/lib/chef/knife/winrm_knife_base.rb +218 -0
  26. data/lib/chef/knife/winrm_session.rb +81 -0
  27. data/lib/chef/knife/winrm_shared_options.rb +47 -0
  28. data/lib/chef/knife/wsman_endpoint.rb +44 -0
  29. data/lib/chef/knife/wsman_test.rb +96 -0
  30. data/lib/knife-windows/path_helper.rb +234 -0
  31. data/lib/knife-windows/version.rb +1 -1
  32. data/spec/assets/win_template_rendered_with_bootstrap_install_command.txt +217 -0
  33. data/spec/assets/win_template_rendered_without_bootstrap_install_command.txt +329 -0
  34. data/spec/assets/win_template_unrendered.txt +246 -0
  35. data/spec/functional/bootstrap_download_spec.rb +129 -35
  36. data/spec/spec_helper.rb +28 -1
  37. data/spec/unit/knife/bootstrap_options_spec.rb +150 -0
  38. data/spec/unit/knife/bootstrap_template_spec.rb +27 -26
  39. data/spec/unit/knife/bootstrap_windows_winrm_spec.rb +166 -32
  40. data/spec/unit/knife/core/windows_bootstrap_context_spec.rb +151 -0
  41. data/spec/unit/knife/windows_cert_generate_spec.rb +90 -0
  42. data/spec/unit/knife/windows_cert_install_spec.rb +51 -0
  43. data/spec/unit/knife/windows_listener_create_spec.rb +76 -0
  44. data/spec/unit/knife/winrm_session_spec.rb +56 -0
  45. data/spec/unit/knife/winrm_spec.rb +403 -118
  46. data/spec/unit/knife/wsman_test_spec.rb +176 -0
  47. metadata +67 -21
data/appveyor.yml ADDED
@@ -0,0 +1,42 @@
1
+ version: "master-{build}"
2
+
3
+ os: Windows Server 2012
4
+ platform:
5
+ - x64
6
+
7
+ environment:
8
+ bundle_gemfile: ci.gemfile
9
+
10
+ matrix:
11
+ - ruby_version: "193"
12
+ chef_version: "< 12"
13
+
14
+ - ruby_version: "200"
15
+ chef_version: "< 12"
16
+
17
+ - ruby_version: "200"
18
+ chef_version: "~> 12.0"
19
+
20
+ - ruby_version: "200"
21
+ chef_version: "master"
22
+
23
+ clone_folder: c:\projects\knife-windows
24
+ clone_depth: 1
25
+ branches:
26
+ only:
27
+ - master
28
+
29
+ install:
30
+ - winrm quickconfig -q
31
+ - SET PATH=C:\Ruby%ruby_version%\bin;%PATH%
32
+ - echo %PATH%
33
+ - ruby --version
34
+ - gem --version
35
+ - gem install bundler --quiet --no-ri --no-rdoc
36
+ - bundler --version
37
+
38
+ build_script:
39
+ - bundle install || bundle install || bundle install
40
+
41
+ test_script:
42
+ - bundle exec rake
data/ci.gemfile ADDED
@@ -0,0 +1,15 @@
1
+ source "https://rubygems.org"
2
+
3
+ # Specify your gem's dependencies in knife-windows.gemspec
4
+ gemspec
5
+
6
+ if ENV['CHEF_VERSION'] == 'master'
7
+ gem 'chef', github: 'chef/chef'
8
+ else
9
+ gem 'chef', ENV['CHEF_VERSION']
10
+ end
11
+
12
+ gem "rspec", '~> 3.0'
13
+ gem "ruby-wmi"
14
+ gem "httpclient"
15
+ gem 'rake'
@@ -7,15 +7,16 @@ Gem::Specification.new do |s|
7
7
  s.version = Knife::Windows::VERSION
8
8
  s.platform = Gem::Platform::RUBY
9
9
  s.authors = ["Seth Chisamore"]
10
- s.email = ["schisamo@opscode.com"]
10
+ s.email = ["schisamo@chef.io"]
11
11
  s.license = "Apache-2.0"
12
- s.homepage = "https://github.com/opscode/knife-windows"
12
+ s.homepage = "https://github.com/chef/knife-windows"
13
13
  s.summary = %q{Plugin that adds functionality to Chef's Knife CLI for configuring/interacting with nodes running Microsoft Windows}
14
14
  s.description = s.summary
15
15
 
16
16
  s.required_ruby_version = ">= 1.9.1"
17
- s.add_dependency "winrm-s", "~> 0.2"
18
- s.add_dependency "em-winrm", "~> 0.6"
17
+ s.add_dependency "winrm", "~> 1.3"
18
+ s.add_dependency "winrm-s", "~> 0.3.0"
19
+ s.add_dependency "nokogiri"
19
20
 
20
21
  s.add_development_dependency 'pry'
21
22
 
@@ -24,3 +25,4 @@ Gem::Specification.new do |s|
24
25
  s.executables = `git ls-files -- bin/*`.split("\n").map{ |f| File.basename(f) }
25
26
  s.require_paths = ["lib"]
26
27
  end
28
+
@@ -105,99 +105,124 @@ goto install
105
105
  goto install
106
106
 
107
107
  :install
108
- @rem Install Chef using chef-client MSI installer
109
-
110
- <% url="https://www.opscode.com/chef/download?p=windows&pv=%MACHINE_OS%&m=%MACHINE_ARCH%" -%>
111
- <% url += "&v=#{@config[:bootstrap_version]}" if @config.key? :bootstrap_version -%>
112
- @set "REMOTE_SOURCE_MSI_URL=<%= url %>"
113
- @set "LOCAL_DESTINATION_MSI_PATH=<%= local_download_path %>"
114
- @set "CHEF_CLIENT_MSI_LOG_PATH=%TEMP%\chef-client-msi%RANDOM%.log"
115
- @set "FALLBACK_QUERY_STRING=&DownloadContext=PowerShell"
116
-
117
- @rem Clear any pre-existing downloads
118
- @echo Checking for existing downloaded package at "%LOCAL_DESTINATION_MSI_PATH%"
119
- @if EXIST "%LOCAL_DESTINATION_MSI_PATH%" (
120
- @echo Found existing downloaded package, deleting.
121
- @del /f /q "%LOCAL_DESTINATION_MSI_PATH%"
122
- @if ERRORLEVEL 1 (
123
- echo Warning: Failed to delete pre-existing package with status code !ERRORLEVEL! > "&2"
108
+ @rem If user has provided the custom installation command for chef-client then execute it
109
+ <% if @chef_config[:knife][:bootstrap_install_command] %>
110
+ <%= @chef_config[:knife][:bootstrap_install_command] %>
111
+ <% else %>
112
+ @rem Install Chef using chef-client MSI installer
113
+
114
+ @set "LOCAL_DESTINATION_MSI_PATH=<%= local_download_path %>"
115
+ @set "CHEF_CLIENT_MSI_LOG_PATH=%TEMP%\chef-client-msi%RANDOM%.log"
116
+
117
+ @rem Clear any pre-existing downloads
118
+ @echo Checking for existing downloaded package at "%LOCAL_DESTINATION_MSI_PATH%"
119
+ @if EXIST "%LOCAL_DESTINATION_MSI_PATH%" (
120
+ @echo Found existing downloaded package, deleting.
121
+ @del /f /q "%LOCAL_DESTINATION_MSI_PATH%"
122
+ @if ERRORLEVEL 1 (
123
+ echo Warning: Failed to delete pre-existing package with status code !ERRORLEVEL! > "&2"
124
+ )
125
+ ) else (
126
+ echo No existing downloaded packages to delete.
124
127
  )
125
- ) else (
126
- echo No existing downloaded packages to delete.
127
- )
128
-
129
- @rem If there is somehow a name collision, remove pre-existing log
130
- @if EXIST "%CHEF_CLIENT_MSI_LOG_PATH%" del /f /q "%CHEF_CLIENT_MSI_LOG_PATH%"
131
128
 
132
- @echo Attempting to download client package using cscript...
133
- cscript /nologo <%= bootstrap_directory %>\wget.vbs /url:"%REMOTE_SOURCE_MSI_URL%" /path:"%LOCAL_DESTINATION_MSI_PATH%"
134
-
135
- @rem Work around issues found in Windows Server 2012 around job objects not respecting WSMAN memory quotas
136
- @rem that cause the MSI download process to exceed the quota even when it is increased by administrators.
137
- @rem Retry the download using a more memory-efficient mechanism that only works if PowerShell is available.
138
- @set DOWNLOAD_ERROR_STATUS=!ERRORLEVEL!
139
- @if ERRORLEVEL 1 (
140
- @echo Failed cscript download with status code !DOWNLOAD_ERROR_STATUS! > "&2"
141
- @if !DOWNLOAD_ERROR_STATUS!==0 set DOWNLOAD_ERROR_STATUS=2
142
- ) else (
143
- @rem Sometimes the error level is not set even when the download failed,
144
- @rem so check for the file to be sure it is there -- if it is not, we will retry
145
- @if NOT EXIST "%LOCAL_DESTINATION_MSI_PATH%" (
146
- echo Failed download: download completed, but downloaded file not found > "&2"
147
- set DOWNLOAD_ERROR_STATUS=2
148
- ) else (
149
- echo Download via cscript succeeded.
129
+ @rem If there is somehow a name collision, remove pre-existing log
130
+ @if EXIST "%CHEF_CLIENT_MSI_LOG_PATH%" del /f /q "%CHEF_CLIENT_MSI_LOG_PATH%"
131
+
132
+ @echo Attempting to download client package using PowerShell if available...
133
+ @set "REMOTE_SOURCE_MSI_URL=<%= msi_url('%MACHINE_OS%', '%MACHINE_ARCH%', 'PowerShell') %>"
134
+ @set powershell_download=powershell.exe -ExecutionPolicy Unrestricted -NoProfile -NonInteractive -File <%= bootstrap_directory %>\wget.ps1 "%REMOTE_SOURCE_MSI_URL%" "%LOCAL_DESTINATION_MSI_PATH%"
135
+ @echo !powershell_download!
136
+ @call !powershell_download!
137
+
138
+ @set DOWNLOAD_ERROR_STATUS=!ERRORLEVEL!
139
+
140
+ @if ERRORLEVEL 1 (
141
+ @echo Failed PowerShell download with status code !DOWNLOAD_ERROR_STATUS! > "&2"
142
+ @if !DOWNLOAD_ERROR_STATUS!==0 set DOWNLOAD_ERROR_STATUS=2
143
+ ) else (
144
+ @rem Sometimes the error level is not set even when the download failed,
145
+ @rem so check for the file to be sure it is there -- if it is not, we will retry
146
+ @if NOT EXIST "%LOCAL_DESTINATION_MSI_PATH%" (
147
+ echo Failed download: download completed, but downloaded file not found > "&2"
148
+ set DOWNLOAD_ERROR_STATUS=2
149
+ ) else (
150
+ echo Download via PowerShell succeeded.
151
+ )
150
152
  )
151
- )
152
153
 
153
- @if NOT %DOWNLOAD_ERROR_STATUS%==0 (
154
- @echo Warning: Failed to download "%REMOTE_SOURCE_MSI_URL%" to "%LOCAL_DESTINATION_MSI_PATH%"
155
- @echo Warning: Retrying download with PowerShell if available...
156
-
157
- @if EXIST "%LOCAL_DESTINATION_MSI_PATH%" del /f /q "%LOCAL_DESTINATION_MSI_PATH%"
158
-
159
- @set powershell_download=powershell.exe -ExecutionPolicy Unrestricted -NoProfile -NonInteractive -File <%= bootstrap_directory %>\wget.ps1 "%REMOTE_SOURCE_MSI_URL%%FALLBACK_QUERY_STRING%" "%LOCAL_DESTINATION_MSI_PATH%"
160
- @echo !powershell_download!
161
- @call !powershell_download!
162
- @if NOT ERRORLEVEL 1 (
163
- echo Download via PowerShell succeeded.
164
- ) else (
165
- echo Failed to download "%REMOTE_SOURCE_MSI_URL%" with status code !ERRORLEVEL!. > "&2"
166
- echo Exiting without bootstrapping due to download failure. > "&2"
167
- exit /b 1
154
+ @if NOT %DOWNLOAD_ERROR_STATUS%==0 (
155
+ @echo Warning: Failed to download "%REMOTE_SOURCE_MSI_URL%" to "%LOCAL_DESTINATION_MSI_PATH%"
156
+ @echo Warning: Retrying download with cscript ...
157
+
158
+ @if EXIST "%LOCAL_DESTINATION_MSI_PATH%" del /f /q "%LOCAL_DESTINATION_MSI_PATH%"
159
+
160
+ @set "REMOTE_SOURCE_MSI_URL=<%= msi_url('%MACHINE_OS%', '%MACHINE_ARCH%') %>"
161
+ cscript /nologo <%= bootstrap_directory %>\wget.vbs /url:"%REMOTE_SOURCE_MSI_URL%" /path:"%LOCAL_DESTINATION_MSI_PATH%"
162
+
163
+ @if NOT ERRORLEVEL 1 (
164
+ @rem Sometimes the error level is not set even when the download failed,
165
+ @rem so check for the file to be sure it is there.
166
+ @if NOT EXIST "%LOCAL_DESTINATION_MSI_PATH%" (
167
+ echo Failed download: download completed, but downloaded file not found > "&2"
168
+ echo Exiting without bootstrapping due to download failure. > "&2"
169
+ exit /b 1
170
+ ) else (
171
+ echo Download via cscript succeeded.
172
+ )
173
+ ) else (
174
+ echo Failed to download "%REMOTE_SOURCE_MSI_URL%" with status code !ERRORLEVEL!. > "&2"
175
+ echo Exiting without bootstrapping due to download failure. > "&2"
176
+ exit /b 1
177
+ )
178
+ )
179
+
180
+ @echo Installing downloaded client package...
181
+
182
+ <%= install_chef %>
183
+
184
+ @if ERRORLEVEL 1 (
185
+ echo Chef-client package failed to install with status code !ERRORLEVEL!. > "&2"
186
+ echo See installation log for additional detail: %CHEF_CLIENT_MSI_LOG_PATH%. > "&2"
187
+ ) else (
188
+ @echo Installation completed successfully
189
+ del /f /q "%CHEF_CLIENT_MSI_LOG_PATH%"
168
190
  )
169
- )
170
-
171
- @echo Installing downloaded client package...
172
-
173
- <%= install_chef %>
174
191
 
175
- @if ERRORLEVEL 1 (
176
- echo Chef-client package failed to install with status code !ERRORLEVEL!. > "&2"
177
- echo See installation log for additional detail: %CHEF_CLIENT_MSI_LOG_PATH%. > "&2"
178
- ) else (
179
- @echo Installation completed successfully
180
- del /f /q "%CHEF_CLIENT_MSI_LOG_PATH%"
181
- )
192
+ <% end %>
182
193
 
183
194
  @endlocal
184
195
 
185
196
  @echo off
197
+
198
+ <% if client_pem -%>
199
+ > <%= bootstrap_directory %>\client.pem (
200
+ <%= escape_and_echo(::File.read(::File.expand_path(client_pem))) %>
201
+ )
202
+ <% end -%>
203
+
186
204
  echo Writing validation key...
187
205
 
206
+ <% if validation_key -%>
188
207
  > <%= bootstrap_directory %>\validation.pem (
189
- <%= validation_key %>
208
+ <%= escape_and_echo(validation_key) %>
190
209
  )
210
+ <% end -%>
191
211
 
192
212
  echo Validation key written.
193
213
  @echo on
194
214
 
195
- <% if @config[:encrypted_data_bag_secret] -%>
215
+ <% if @config[:secret] -%>
196
216
  > <%= bootstrap_directory %>\encrypted_data_bag_secret (
197
- <%= encrypted_data_bag_secret %>
217
+ <%= secret %>
198
218
  )
199
219
  <% end -%>
200
220
 
221
+ <% unless trusted_certs_script.empty? -%>
222
+ mkdir <%= bootstrap_directory %>\trusted_certs
223
+ <%= trusted_certs_script %>
224
+ <% end -%>
225
+
201
226
  <%# Generate Ohai Hints -%>
202
227
  <% unless @chef_config[:knife][:hints].nil? || @chef_config[:knife][:hints].empty? -%>
203
228
  mkdir <%= bootstrap_directory %>\ohai\hints
@@ -17,13 +17,19 @@
17
17
  #
18
18
 
19
19
  require 'chef/knife'
20
+ require 'chef/knife/bootstrap'
20
21
  require 'chef/encrypted_data_bag_item'
21
22
  require 'chef/knife/core/windows_bootstrap_context'
23
+ require 'chef/knife/knife_windows_base'
24
+ # Chef 11 PathHelper doesn't have #home
25
+ #require 'chef/util/path_helper'
22
26
 
23
27
  class Chef
24
28
  class Knife
25
29
  module BootstrapWindowsBase
26
30
 
31
+ include Chef::Knife::KnifeWindowsBase
32
+
27
33
  # :nodoc:
28
34
  # Would prefer to do this in a rational way, but can't be done b/c of
29
35
  # Mixlib::CLI's design :(
@@ -55,20 +61,38 @@ class Chef
55
61
  :proc => Proc.new { |p| Chef::Config[:knife][:bootstrap_proxy] = p }
56
62
 
57
63
  option :bootstrap_no_proxy,
58
- :long => "--bootstrap-no-proxy ",
59
- :description => "Avoid a proxy server for the given addresses",
64
+ :long => "--bootstrap-no-proxy [NO_PROXY_URL|NO_PROXY_IP]",
65
+ :description => "Do not proxy locations for the node being bootstrapped; this option is used internally by Opscode",
60
66
  :proc => Proc.new { |np| Chef::Config[:knife][:bootstrap_no_proxy] = np }
61
67
 
68
+ option :bootstrap_install_command,
69
+ :long => "--bootstrap-install-command COMMANDS",
70
+ :description => "Custom command to install chef-client",
71
+ :proc => Proc.new { |ic| Chef::Config[:knife][:bootstrap_install_command] = ic }
72
+
73
+ # DEPR: Remove this option in Chef 13
62
74
  option :distro,
63
75
  :short => "-d DISTRO",
64
76
  :long => "--distro DISTRO",
65
- :description => "Bootstrap a distro using a template",
66
- :default => "windows-chef-client-msi"
67
-
77
+ :description => "Bootstrap a distro using a template. [DEPRECATED] Use -t / --bootstrap-template option instead.",
78
+ :proc => Proc.new { |v|
79
+ Chef::Log.warn("[DEPRECATED] -d / --distro option is deprecated. Use --bootstrap-template option instead.")
80
+ v
81
+ }
82
+
83
+ option :bootstrap_template,
84
+ :short => "-t TEMPLATE",
85
+ :long => "--bootstrap-template TEMPLATE",
86
+ :description => "Bootstrap Chef using a built-in or custom template. Set to the full path of an erb template or use one of the built-in templates."
87
+
88
+ # DEPR: Remove this option in Chef 13
68
89
  option :template_file,
69
90
  :long => "--template-file TEMPLATE",
70
- :description => "Full path to location of template to use",
71
- :default => false
91
+ :description => "Full path to location of template to use. [DEPRECATED] Use -t / --bootstrap-template option instead.",
92
+ :proc => Proc.new { |v|
93
+ Chef::Log.warn("[DEPRECATED] --template-file option is deprecated. Use --bootstrap-template option instead.")
94
+ v
95
+ }
72
96
 
73
97
  option :run_list,
74
98
  :short => "-r RUN_LIST",
@@ -77,6 +101,15 @@ class Chef
77
101
  :proc => lambda { |o| o.split(",") },
78
102
  :default => []
79
103
 
104
+ option :hint,
105
+ :long => "--hint HINT_NAME[=HINT_FILE]",
106
+ :description => "Specify Ohai Hint to be set on the bootstrap target. Use multiple --hint options to specify multiple hints.",
107
+ :proc => Proc.new { |h|
108
+ Chef::Config[:knife][:hints] ||= Hash.new
109
+ name, path = h.split("=")
110
+ Chef::Config[:knife][:hints][name] = path ? Chef::JSONCompat.parse(::File.read(path)) : Hash.new
111
+ }
112
+
80
113
  option :first_boot_attributes,
81
114
  :short => "-j JSON_ATTRIBS",
82
115
  :long => "--json-attributes",
@@ -84,12 +117,14 @@ class Chef
84
117
  :proc => lambda { |o| JSON.parse(o) },
85
118
  :default => {}
86
119
 
120
+ # Mismatch between option 'encrypted_data_bag_secret' and it's long value '--secret' is by design for compatibility
87
121
  option :encrypted_data_bag_secret,
88
122
  :short => "-s SECRET",
89
123
  :long => "--secret ",
90
124
  :description => "The secret key to use to decrypt data bag item values. Will be rendered on the node at c:/chef/encrypted_data_bag_secret and set in the rendered client config.",
91
125
  :default => false
92
126
 
127
+ # Mismatch between option 'encrypted_data_bag_secret_file' and it's long value '--secret-file' is by design for compatibility
93
128
  option :encrypted_data_bag_secret_file,
94
129
  :long => "--secret-file SECRET_FILE",
95
130
  :description => "A file containing the secret key to use to encrypt data bag item values. Will be rendered on the node at c:/chef/encrypted_data_bag_secret and set in the rendered client config."
@@ -98,23 +133,91 @@ class Chef
98
133
  :long => "--auth-timeout MINUTES",
99
134
  :description => "The maximum time in minutes to wait to for authentication over the transport to the node to succeed. The default value is 2 minutes.",
100
135
  :default => 2
136
+
137
+ option :node_ssl_verify_mode,
138
+ :long => "--node-ssl-verify-mode [peer|none]",
139
+ :description => "Whether or not to verify the SSL cert for all HTTPS requests.",
140
+ :proc => Proc.new { |v|
141
+ valid_values = ["none", "peer"]
142
+ unless valid_values.include?(v)
143
+ raise "Invalid value '#{v}' for --node-ssl-verify-mode. Valid values are: #{valid_values.join(", ")}"
144
+ end
145
+ }
146
+
147
+ option :node_verify_api_cert,
148
+ :long => "--[no-]node-verify-api-cert",
149
+ :description => "Verify the SSL cert for HTTPS requests to the Chef server API.",
150
+ :boolean => true
151
+
152
+ option :msi_url,
153
+ :short => "-u URL",
154
+ :long => "--msi-url URL",
155
+ :description => "Location of the Chef Client MSI. The default templates will prefer to download from this location. The MSI will be downloaded from chef.io if not provided.",
156
+ :default => ''
157
+
158
+ option :install_as_service,
159
+ :long => "--install-as-service",
160
+ :description => "Install chef-client as a Windows service",
161
+ :default => false
162
+
163
+ option :bootstrap_vault_file,
164
+ :long => '--bootstrap-vault-file VAULT_FILE',
165
+ :description => 'A JSON file with a list of vault(s) and item(s) to be updated'
166
+
167
+ option :bootstrap_vault_json,
168
+ :long => '--bootstrap-vault-json VAULT_JSON',
169
+ :description => 'A JSON string with the vault(s) and item(s) to be updated'
170
+
171
+ option :bootstrap_vault_item,
172
+ :long => '--bootstrap-vault-item VAULT_ITEM',
173
+ :description => 'A single vault and item to update as "vault:item"',
174
+ :proc => Proc.new { |i|
175
+ (vault, item) = i.split(/:/)
176
+ Chef::Config[:knife][:bootstrap_vault_item] ||= {}
177
+ Chef::Config[:knife][:bootstrap_vault_item][vault] ||= []
178
+ Chef::Config[:knife][:bootstrap_vault_item][vault].push(item)
179
+ Chef::Config[:knife][:bootstrap_vault_item]
180
+ }
181
+
182
+ option :tags,
183
+ :long => "--tags TAGS",
184
+ :description => "Comma separated list of tags to apply to the node",
185
+ :proc => lambda { |o| o.split(/[\s,]+/) },
186
+ :default => []
101
187
  end
102
188
  end
103
189
 
104
- # TODO: This should go away when CHEF-2193 is fixed
190
+ def default_bootstrap_template
191
+ "windows-chef-client-msi"
192
+ end
193
+
194
+ def bootstrap_template
195
+ # The order here is important. We want to check if we have the new Chef 12 option is set first.
196
+ # Knife cloud plugins unfortunately all set a default option for the :distro so it should be at
197
+ # the end.
198
+ config[:bootstrap_template] || config[:template_file] || config[:distro] || default_bootstrap_template
199
+ end
200
+
201
+ # TODO: This should go away when CHEF-2193 is fixed
105
202
  def load_template(template=nil)
106
203
  # Are we bootstrapping using an already shipped template?
107
- if config[:template_file]
108
- bootstrap_files = config[:template_file]
109
- else
110
- bootstrap_files = []
111
- bootstrap_files << File.join(File.dirname(__FILE__), 'bootstrap', "#{config[:distro]}.erb")
112
- bootstrap_files << File.join(Dir.pwd, ".chef", "bootstrap", "#{config[:distro]}.erb")
113
- bootstrap_files << File.join(ENV['HOME'], '.chef', 'bootstrap', "#{config[:distro]}.erb")
114
- bootstrap_files << Gem.find_files(File.join("chef","knife","bootstrap","#{config[:distro]}.erb"))
115
- bootstrap_files.flatten!
204
+
205
+ template = bootstrap_template
206
+
207
+ # Use the template directly if it's a path to an actual file
208
+ if File.exists?(template)
209
+ Chef::Log.debug("Using the specified bootstrap template: #{File.dirname(template)}")
210
+ return IO.read(template).chomp
116
211
  end
117
212
 
213
+ # Otherwise search the template directories until we find the right one
214
+ bootstrap_files = []
215
+ bootstrap_files << File.join(File.dirname(__FILE__), 'bootstrap/templates', "#{template}.erb")
216
+ bootstrap_files << File.join(Knife.chef_config_dir, "bootstrap", "#{template}.erb") if Chef::Knife.chef_config_dir
217
+ ::Knife::Windows::PathHelper.all_homes('.chef', 'bootstrap', "#{template}.erb") { |p| bootstrap_files << p }
218
+ bootstrap_files << Gem.find_files(File.join("chef","knife","bootstrap","#{template}.erb"))
219
+ bootstrap_files.flatten!
220
+
118
221
  template = Array(bootstrap_files).find do |bootstrap_template|
119
222
  Chef::Log.debug("Looking for bootstrap template in #{File.dirname(bootstrap_template)}")
120
223
  ::File.exists?(bootstrap_template)
@@ -130,15 +233,35 @@ class Chef
130
233
  IO.read(template).chomp
131
234
  end
132
235
 
236
+ def bootstrap_context
237
+ @bootstrap_context ||= Knife::Core::WindowsBootstrapContext.new(config, config[:run_list], Chef::Config)
238
+ end
239
+
240
+ def load_correct_secret
241
+ knife_secret_file = Chef::Config[:knife][:encrypted_data_bag_secret_file]
242
+ knife_secret = Chef::Config[:knife][:encrypted_data_bag_secret]
243
+ cli_secret_file = config[:encrypted_data_bag_secret_file]
244
+ cli_secret = config[:encrypted_data_bag_secret]
245
+
246
+ cli_secret_file = nil if cli_secret_file == knife_secret_file
247
+ cli_secret = nil if cli_secret == knife_secret
248
+
249
+ cli_secret_file = Chef::EncryptedDataBagItem.load_secret(cli_secret_file) if cli_secret_file != nil
250
+ knife_secret_file = Chef::EncryptedDataBagItem.load_secret(knife_secret_file) if knife_secret_file != nil
251
+
252
+ cli_secret_file || cli_secret || knife_secret_file || knife_secret
253
+ end
254
+
133
255
  def render_template(template=nil)
134
- if config[:encrypted_data_bag_secret_file]
135
- config[:encrypted_data_bag_secret] = Chef::EncryptedDataBagItem.load_secret(config[:encrypted_data_bag_secret_file])
136
- end
137
- context = Knife::Core::WindowsBootstrapContext.new(config, config[:run_list], Chef::Config)
138
- Erubis::Eruby.new(template).evaluate(context)
256
+ config[:secret] = load_correct_secret
257
+ Erubis::Eruby.new(template).evaluate(bootstrap_context)
139
258
  end
140
259
 
141
260
  def bootstrap(proto=nil)
261
+ if Chef::Config[:knife][:encrypted_data_bag_secret_file] || Chef::Config[:knife][:encrypted_data_bag_secret]
262
+ warn_chef_config_secret_key
263
+ end
264
+
142
265
  validate_name_args!
143
266
 
144
267
  @node_name = Array(@name_args).first
@@ -147,13 +270,34 @@ class Chef
147
270
 
148
271
  STDOUT.sync = STDERR.sync = true
149
272
 
273
+ if (Chef::Config[:validation_key] && !File.exist?(File.expand_path(Chef::Config[:validation_key])))
274
+ if Chef::VERSION.split('.').first.to_i == 11
275
+ ui.error("Unable to find validation key. Please verify your configuration file for validation_key config value.")
276
+ exit 1
277
+ end
278
+
279
+ unless locate_config_value(:chef_node_name)
280
+ ui.error("You must pass a node name with -N when bootstrapping with user credentials")
281
+ exit 1
282
+ end
283
+
284
+ chef_vault_handler.run(node_name: config[:chef_node_name]) if chef_vault_handler.doing_chef_vault?
285
+
286
+ client_builder.run
287
+ bootstrap_context.client_pem = client_builder.client_path
288
+ else
289
+ ui.info("Doing old-style registration with the validation key at #{Chef::Config[:validation_key]}...")
290
+ ui.info("Delete your validation key in order to use your user credentials instead")
291
+ ui.info("")
292
+ end
293
+
150
294
  wait_for_remote_response( config[:auth_timeout].to_i )
151
295
  ui.info("Bootstrapping Chef on #{ui.color(@node_name, :bold)}")
152
296
  # create a bootstrap.bat file on the node
153
297
  # we have to run the remote commands in 2047 char chunks
154
- create_bootstrap_bat_command do |command_chunk, chunk_num|
298
+ create_bootstrap_bat_command do |command_chunk|
155
299
  begin
156
- render_command_result = run_command(%Q!cmd.exe /C echo "Rendering #{bootstrap_bat_file} chunk #{chunk_num}" && #{command_chunk}!)
300
+ render_command_result = run_command(command_chunk)
157
301
  ui.error("Batch render command returned #{render_command_result}") if render_command_result != 0
158
302
  render_command_result
159
303
  rescue SystemExit => e
@@ -164,6 +308,7 @@ class Chef
164
308
  # execute the bootstrap.bat file
165
309
  bootstrap_command_result = run_command(bootstrap_command)
166
310
  ui.error("Bootstrap command returned #{bootstrap_command_result}") if bootstrap_command_result != 0
311
+
167
312
  bootstrap_command_result
168
313
  end
169
314
 
@@ -177,29 +322,66 @@ class Chef
177
322
  @bootstrap_command ||= "cmd.exe /C #{bootstrap_bat_file}"
178
323
  end
179
324
 
180
- def create_bootstrap_bat_command(&block)
181
- bootstrap_bat = []
325
+ def bootstrap_render_banner_command(chunk_num)
326
+ "cmd.exe /C echo Rendering #{bootstrap_bat_file} chunk #{chunk_num}"
327
+ end
328
+
329
+ def escape_windows_batch_characters(line)
330
+ # TODO: The commands are going to get redirected - do we need to escape &?
331
+ line.gsub!(/[(<|>)^]/).each{|m| "^#{m}"}
332
+ end
333
+
334
+ def create_bootstrap_bat_command()
182
335
  chunk_num = 0
336
+ bootstrap_bat = ""
337
+ banner = bootstrap_render_banner_command(chunk_num += 1)
183
338
  render_template(load_template(config[:bootstrap_template])).each_line do |line|
184
- # escape WIN BATCH special chars
185
- line.gsub!(/[(<|>)^]/).each{|m| "^#{m}"}
186
- # windows commands are limited to 2047 characters
187
- if((bootstrap_bat + [line]).join(" && ").size > 2047 )
188
- yield bootstrap_bat.join(" && "), chunk_num += 1
189
- bootstrap_bat = []
339
+ escape_windows_batch_characters(line)
340
+ # We are guaranteed to have a prefix "banner" command that echo's chunk number. We can
341
+ # confidently prefix every actual command with &&.
342
+ # TODO: Why does ^\n&& work directly through the commandline but not through SOAP?
343
+ render_line = " && >> #{bootstrap_bat_file} (echo.#{line.chomp.strip})"
344
+ # Windows commands are limited to 8191 characters for machines running XP or higher but
345
+ # this includes the length of environment variables after they have been expanded.
346
+ # Since we don't actually know how long %TEMP% (and it's used twice - once in the banner
347
+ # and once in every command redirection), we simply guess and set the max to 5000.
348
+ # TODO: When a more accurate method is available, fix this.
349
+ if bootstrap_bat.length + render_line.length + banner.length > 5000
350
+ # Can't fit it into this chunk? - flush (if necessary) and then try.
351
+ # Do this first because banner.length might change (e.g. due to an extra digit) and
352
+ # prevent a fit.
353
+ unless bootstrap_bat.empty?
354
+ yield banner + bootstrap_bat
355
+ bootstrap_bat = ""
356
+ banner = bootstrap_render_banner_command(chunk_num += 1)
357
+ end
358
+ # Will this ever fit?
359
+ if render_line.length + banner.length > 5000
360
+ raise "Command in bootstrap template too long by #{render_line.length + banner.length - 5000} characters : #{line}"
361
+ end
190
362
  end
191
- bootstrap_bat << ">> #{bootstrap_bat_file} (echo.#{line.chomp.strip})"
363
+ bootstrap_bat << render_line
192
364
  end
193
- yield bootstrap_bat.join(" && "), chunk_num += 1
365
+ raise "Bootstrap template was empty! Check #{config[:bootstrap_template]}" if bootstrap_bat.empty?
366
+ yield banner + bootstrap_bat
194
367
  end
195
368
 
196
369
  def bootstrap_bat_file
197
370
  @bootstrap_bat_file ||= "\"%TEMP%\\bootstrap-#{Process.pid}-#{Time.now.to_i}.bat\""
198
371
  end
199
372
 
200
- def locate_config_value(key)
201
- key = key.to_sym
202
- Chef::Config[:knife][key] || config[key]
373
+ def warn_chef_config_secret_key
374
+ ui.info "* " * 40
375
+ ui.warn(<<-WARNING)
376
+ \nSpecifying the encrypted data bag secret key using an 'encrypted_data_bag_secret'
377
+ entry in 'knife.rb' is deprecated. Please use the '--secret' or '--secret-file'
378
+ options of this command instead.
379
+
380
+ #{ui.color('IMPORTANT:', :red, :bold)} In a future version of Chef, this
381
+ behavior will be removed and any 'encrypted_data_bag_secret' entries in
382
+ 'knife.rb' will be ignored completely.
383
+ WARNING
384
+ ui.info "* " * 40
203
385
  end
204
386
  end
205
387
  end