Class: Chef::Knife::Core::WindowsBootstrapContext

Inherits:
BootstrapContext show all
Defined in:
lib/chef/knife/core/windows_bootstrap_context.rb

Overview

Instances of BootstrapContext are the context objects (i.e., self) for bootstrap templates. For backwards compatibility, they must set the following instance variables:

  • @config - a hash of knife’s config values

  • @run_list - the run list for the node to bootstrap

Instance Attribute Summary collapse

Attributes inherited from BootstrapContext

#client_pem

Instance Method Summary collapse

Methods inherited from BootstrapContext

#bootstrap_environment, #chef_ice?, #client_d, #detect_package_manager, #product_to_install, #trusted_certs, #version_to_install

Constructor Details

#initialize(config, run_list, chef_config, secret = nil) ⇒ WindowsBootstrapContext

Returns a new instance of WindowsBootstrapContext.



37
38
39
40
41
42
43
# File 'lib/chef/knife/core/windows_bootstrap_context.rb', line 37

def initialize(config, run_list, chef_config, secret = nil)
  @config       = config
  @run_list     = run_list
  @chef_config  = chef_config
  @secret       = secret
  super(config, run_list, chef_config, secret)
end

Instance Attribute Details

#chef_configObject

Returns the value of attribute chef_config.



34
35
36
# File 'lib/chef/knife/core/windows_bootstrap_context.rb', line 34

def chef_config
  @chef_config
end

#configObject

Returns the value of attribute config.



33
34
35
# File 'lib/chef/knife/core/windows_bootstrap_context.rb', line 33

def config
  @config
end

#secretObject

Returns the value of attribute secret.



35
36
37
# File 'lib/chef/knife/core/windows_bootstrap_context.rb', line 35

def secret
  @secret
end

Instance Method Details

#bootstrap_directoryObject



371
372
373
# File 'lib/chef/knife/core/windows_bootstrap_context.rb', line 371

def bootstrap_directory
  ChefConfig::Config.etc_chef_dir(windows: true)
end

#build_chef_executableObject



203
204
205
206
207
208
209
210
211
212
213
214
215
216
# File 'lib/chef/knife/core/windows_bootstrap_context.rb', line 203

def build_chef_executable
  # For --bootstrap-url, use conditional logic based on chef_ice? since we don't know what the script installs
  if config[:bootstrap_url] && !config[:bootstrap_url].empty?
    if chef_ice?
      # Set HAB_LICENSE to auto-accept Habitat license for non-interactive bootstrap
      "SET \"HAB_LICENSE=accept-no-persist\"\nhab pkg exec chef/chef-infra-client #{ChefUtils::Dist::Infra::CLIENT}"
    else
      ChefUtils::Dist::Infra::CLIENT
    end
  else
    # For default/msi flows, use standard chef-client
    ChefUtils::Dist::Infra::CLIENT
  end
end

#build_environment_optionObject



229
230
231
# File 'lib/chef/knife/core/windows_bootstrap_context.rb', line 229

def build_environment_option
  bootstrap_environment.nil? ? "" : " -E #{bootstrap_environment}"
end

#build_license_argumentObject



218
219
220
221
222
223
224
225
226
227
# File 'lib/chef/knife/core/windows_bootstrap_context.rb', line 218

def build_license_argument
  return "" if config[:disable_license_activation]
  return "" unless chef_ice? && config[:license_id]

  # Skip license flag when using custom MSI or bootstrap URLs
  return "" if config[:msi_url] && !config[:msi_url].empty?
  return "" if config[:bootstrap_url] && !config[:bootstrap_url].empty?

  " --chef-license-key #{config[:license_id]}"
end

#build_path_commandObject



183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
# File 'lib/chef/knife/core/windows_bootstrap_context.rb', line 183

def build_path_command
  base_path = "SET \"PATH=%SYSTEM32%;%SystemRoot%;%SYSTEM32%\\Wbem;%SYSTEM32%\\WindowsPowerShell\\v1.0\\;"

  # For --bootstrap-url, use conditional logic based on chef_ice? since we don't know what the script installs
  if config[:bootstrap_url] && !config[:bootstrap_url].empty?
    additional_paths = if chef_ice?
                         "C:\\hab\\bin"
                       else
                         c_opscode_dir = ChefConfig::PathHelper.cleanpath(ChefConfig::Config.c_opscode_dir, windows: true)
                         "C:\\ruby\\bin;#{c_opscode_dir}\\bin;#{c_opscode_dir}\\embedded\\bin"
                       end
  else
    # For default/msi flows, use standard paths
    c_opscode_dir = ChefConfig::PathHelper.cleanpath(ChefConfig::Config.c_opscode_dir, windows: true)
    additional_paths = "C:\\ruby\\bin;#{c_opscode_dir}\\bin;#{c_opscode_dir}\\embedded\\bin;C:\\hab\\bin"
  end

  "#{base_path}#{additional_paths};%PATH%\"\n"
end

#clean_etc_chef_file(path) ⇒ Object



363
364
365
# File 'lib/chef/knife/core/windows_bootstrap_context.rb', line 363

def clean_etc_chef_file(path)
  ChefConfig::PathHelper.cleanpath(etc_chef_file(path), windows: true)
end

#config_contentObject



61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
# File 'lib/chef/knife/core/windows_bootstrap_context.rb', line 61

def config_content
  # The windows: true / windows: false in the block that follows is more than a bit weird.  The way to read this is that we need
  # the e.g. var_chef_dir to be rendered for the windows value ("C:\chef"), but then we are rendering into a file to be read by
  # ruby, so we don't actually care about forward-vs-backslashes and by rendering into unix we avoid having to deal with the
  # double-backwhacking of everything.  So we expect to see:
  #
  # file_cache_path "C:/chef"
  #
  # Which is mildly odd, but should be entirely correct as far as ruby cares.
  #
  client_rb = <<~CONFIG
    chef_server_url  "#{chef_config[:chef_server_url]}"
    validation_client_name "#{chef_config[:validation_client_name]}"
    file_cache_path   "#{ChefConfig::PathHelper.escapepath(chef_config[:windows_bootstrap_file_cache_path] || "")}"
    file_backup_path  "#{ChefConfig::PathHelper.escapepath(chef_config[:windows_bootstrap_file_backup_path] || "")}"
    cache_options     ({:path => "#{ChefConfig::PathHelper.escapepath(ChefConfig::Config.etc_chef_dir(windows: true))}\\\\cache\\\\checksums", :skip_expires => true})
  CONFIG

  unless chef_config[:chef_license].nil?
    client_rb << "chef_license \"#{chef_config[:chef_license]}\"\n"
  end

  if config[:chef_node_name]
    client_rb << %Q{node_name "#{config[:chef_node_name]}"\n}
  else
    client_rb << "# Using default node name (fqdn)\n"
  end

  if chef_config[:config_log_level]
    client_rb << %Q{log_level :#{chef_config[:config_log_level]}\n}
  else
    client_rb << "log_level        :auto\n"
  end

  client_rb << "log_location       #{get_log_location}"

  # We configure :verify_api_cert only when it's overridden on the CLI
  # or when specified in the knife config.
  if !config[:node_verify_api_cert].nil? || config.key?(:verify_api_cert)
    value = config[:node_verify_api_cert].nil? ? config[:verify_api_cert] : config[:node_verify_api_cert]
    client_rb << %Q{verify_api_cert #{value}\n}
  end

  # We configure :ssl_verify_mode only when it's overridden on the CLI
  # or when specified in the knife config.
  if config[:node_ssl_verify_mode] || config.key?(:ssl_verify_mode)
    value = case config[:node_ssl_verify_mode]
            when "peer"
              :verify_peer
            when "none"
              :verify_none
            when nil
              config[:ssl_verify_mode]
            else
              nil
            end

    if value
      client_rb << %Q{ssl_verify_mode :#{value}\n}
    end
  end

  if config[:ssl_verify_mode]
    client_rb << %Q{ssl_verify_mode :#{config[:ssl_verify_mode]}\n}
  end

  if config[:bootstrap_proxy]
    client_rb << "\n"
    client_rb << %Q{http_proxy        "#{config[:bootstrap_proxy]}"\n}
    client_rb << %Q{https_proxy       "#{config[:bootstrap_proxy]}"\n}
    client_rb << %Q{no_proxy          "#{config[:bootstrap_no_proxy]}"\n} if config[:bootstrap_no_proxy]
  end

  if config[:bootstrap_no_proxy]
    client_rb << %Q{no_proxy       "#{config[:bootstrap_no_proxy]}"\n}
  end

  if secret
    client_rb << %Q{encrypted_data_bag_secret "#{ChefConfig::PathHelper.escapepath(ChefConfig::Config.etc_chef_dir(windows: true))}\\\\encrypted_data_bag_secret"\n}
  end

  unless trusted_certs_script.empty?
    client_rb << %Q{trusted_certs_dir "#{ChefConfig::PathHelper.escapepath(ChefConfig::Config.etc_chef_dir(windows: true))}\\\\trusted_certs"\n}
  end

  if chef_config[:fips]
    client_rb << "fips true\n"
  end

  escape_and_echo(client_rb)
end

#encrypted_data_bag_secretObject



53
54
55
# File 'lib/chef/knife/core/windows_bootstrap_context.rb', line 53

def encrypted_data_bag_secret
  escape_and_echo(@secret)
end

#escape_and_echo(file_contents) ⇒ Object

escape WIN BATCH special chars and prefixes each line with an echo



389
390
391
# File 'lib/chef/knife/core/windows_bootstrap_context.rb', line 389

def escape_and_echo(file_contents)
  file_contents.gsub(/^(.*)$/, 'echo.\1').gsub(/([(<|>)^])/, '^\1')
end

#etc_chef_file(path) ⇒ Object



367
368
369
# File 'lib/chef/knife/core/windows_bootstrap_context.rb', line 367

def etc_chef_file(path)
  "#{bootstrap_directory}/#{path}"
end

#first_bootObject



359
360
361
# File 'lib/chef/knife/core/windows_bootstrap_context.rb', line 359

def first_boot
  escape_and_echo(super.to_json)
end

#get_log_locationObject



153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
# File 'lib/chef/knife/core/windows_bootstrap_context.rb', line 153

def get_log_location
  if chef_config[:config_log_location].equal?(:win_evt)
    %Q{:#{chef_config[:config_log_location]}\n}
  elsif chef_config[:config_log_location].equal?(:syslog)
    raise "syslog is not supported for log_location on Windows OS\n"
  elsif chef_config[:config_log_location].equal?(STDOUT)
    "STDOUT\n"
  elsif chef_config[:config_log_location].equal?(STDERR)
    "STDERR\n"
  elsif chef_config[:config_log_location].nil? || chef_config[:config_log_location].empty?
    "STDOUT\n"
  elsif chef_config[:config_log_location]
    %Q{"#{chef_config[:config_log_location]}"\n}
  else
    "STDOUT\n"
  end
end

#install_ps1_urlObject

Build a URL for the PowerShell install script (install.ps1)



376
377
378
379
380
381
382
383
384
# File 'lib/chef/knife/core/windows_bootstrap_context.rb', line 376

def install_ps1_url
  if config[:bootstrap_url]
    # Use custom bootstrap URL if provided
    config[:bootstrap_url]
  elsif config[:license_url]
    # Use license-aware install script URL
    config[:license_url].gsub("install.sh", "install.ps1")
  end
end

#msi_urlObject

Returns the MSI URL for downloading Chef Infra Client Supports both chef and chef-ice products, and custom URLs



395
396
397
398
# File 'lib/chef/knife/core/windows_bootstrap_context.rb', line 395

def msi_url
  # If a custom MSI URL is provided, use it directly
  config[:msi_url] if config[:msi_url] && !config[:msi_url].empty?
end

#start_chefObject



171
172
173
174
175
176
177
178
179
180
181
# File 'lib/chef/knife/core/windows_bootstrap_context.rb', line 171

def start_chef
  path_command = build_path_command
  chef_executable = build_chef_executable
  license_argument = build_license_argument

  client_rb = clean_etc_chef_file("client.rb")
  first_boot = clean_etc_chef_file("first-boot.json")
  bootstrap_environment_option = build_environment_option

  "#{path_command}#{chef_executable} -c #{client_rb} -j #{first_boot}#{bootstrap_environment_option}#{license_argument}\n"
end

#trusted_certs_scriptObject



57
58
59
# File 'lib/chef/knife/core/windows_bootstrap_context.rb', line 57

def trusted_certs_script
  @trusted_certs_script ||= trusted_certs_content
end

#validation_keyObject



45
46
47
48
49
50
51
# File 'lib/chef/knife/core/windows_bootstrap_context.rb', line 45

def validation_key
  if File.exist?(File.expand_path(chef_config[:validation_key]))
    File.read(File.expand_path(chef_config[:validation_key]))
  else
    false
  end
end

#win_wgetObject



233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
# File 'lib/chef/knife/core/windows_bootstrap_context.rb', line 233

def win_wget
  # I tried my best to figure out how to properly url decode and switch / to \
  # but this is VBScript - so I don't really care that badly.
  win_wget = <<~WGET
    url = WScript.Arguments.Named("url")
    path = WScript.Arguments.Named("path")
    proxy = null
    '* Vaguely attempt to handle file:// scheme urls by url unescaping and switching all
    '* / into . Also assume that file:/// is a local absolute path and that file://<foo>
    '* is possibly a network file path.
    If InStr(url, "file://") = 1 Then
    url = Unescape(url)
    If InStr(url, "file:///") = 1 Then
    sourcePath = Mid(url, Len("file:///") + 1)
    Else
    sourcePath = Mid(url, Len("file:") + 1)
    End If
    sourcePath = Replace(sourcePath, "/", "\\")

    Set objFSO = CreateObject("Scripting.FileSystemObject")
    If objFSO.Fileexists(path) Then objFSO.DeleteFile path
    objFSO.CopyFile sourcePath, path, true
    Set objFSO = Nothing

    Else
    Set objXMLHTTP = CreateObject("MSXML2.ServerXMLHTTP")
    Set wshShell = CreateObject( "WScript.Shell" )
    Set objUserVariables = wshShell.Environment("USER")

    rem http proxy is optional
    rem attempt to read from HTTP_PROXY env var first
    On Error Resume Next

    If NOT (objUserVariables("HTTP_PROXY") = "") Then
    proxy = objUserVariables("HTTP_PROXY")

    rem fall back to named arg
    ElseIf NOT (WScript.Arguments.Named("proxy") = "") Then
    proxy = WScript.Arguments.Named("proxy")
    End If

    If NOT isNull(proxy) Then
    rem setProxy method is only available on ServerXMLHTTP 6.0+
    Set objXMLHTTP = CreateObject("MSXML2.ServerXMLHTTP.6.0")
    objXMLHTTP.setProxy 2, proxy
    End If

    On Error Goto 0

    objXMLHTTP.open "GET", url, false
    objXMLHTTP.send()
    If objXMLHTTP.Status = 200 Then
    Set objADOStream = CreateObject("ADODB.Stream")
    objADOStream.Open
    objADOStream.Type = 1
    objADOStream.Write objXMLHTTP.ResponseBody
    objADOStream.Position = 0
    Set objFSO = Createobject("Scripting.FileSystemObject")
    If objFSO.Fileexists(path) Then objFSO.DeleteFile path
    Set objFSO = Nothing
    objADOStream.SaveToFile path
    objADOStream.Close
    Set objADOStream = Nothing
    ElseIf objXMLHTTP.Status = 400 Then
    errorBody = objXMLHTTP.ResponseText
    WScript.Echo "Error: 400 BadRequest"
    WScript.Echo "Error Body:"
    WScript.Echo errorBody
    Else
    WScript.Echo "An error occurred while downloading the file:"
    errorBody = objXMLHTTP.ResponseText
    WScript.Echo "Status: "
    WScript.Echo objXMLHTTP.Status
    WScript.Echo "Status Text: "
    WScript.Echo errorBody
    End If
    Set objXMLHTTP = Nothing
    End If
  WGET
  escape_and_echo(win_wget)
end

#win_wget_psObject



315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
# File 'lib/chef/knife/core/windows_bootstrap_context.rb', line 315

def win_wget_ps
  win_wget_ps = <<~WGET_PS
    param(
       [String] $remoteUrl,
       [String] $localPath
    )

    [Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12

    $ProxyUrl = $env:http_proxy;
    $webClient = new-object System.Net.WebClient;

    if ($ProxyUrl -ne '') {
      $WebProxy = New-Object System.Net.WebProxy($ProxyUrl,$true)
      $WebClient.Proxy = $WebProxy
    }

    try {
      $webClient.DownloadFile($remoteUrl, $localPath);

      Write-Host "Download complete. The file has been saved to $localPath."
    } catch [System.Net.WebException] {
      $response = $_.Exception.Response

      if ($response.StatusCode -eq [System.Net.HttpStatusCode]::BadRequest) {
        $streamReader = New-Object System.IO.StreamReader($response.GetResponseStream())
        $errorBody = $streamReader.ReadToEnd()
        $streamReader.Dispose()

        Write-Host "Error: 400 BadRequest"
        Write-Host "Error Body:"
        Write-Host $errorBody
      }
      else {
        Write-Host "An error occurred while downloading the file:"
        Write-Host $_.Exception.Message
      }
      Exit 1
    }
  WGET_PS

  escape_and_echo(win_wget_ps)
end