Module: Chef::Knife::BootstrapWindowsBase

Includes:
KnifeWindowsBase
Included in:
BootstrapWindowsSsh, BootstrapWindowsWinrm
Defined in:
lib/chef/knife/bootstrap_windows_base.rb

Class Method Summary collapse

Instance Method Summary collapse

Methods included from KnifeWindowsBase

#locate_config_value

Class Method Details

.included(includer) ⇒ Object

:nodoc: Would prefer to do this in a rational way, but can’t be done b/c of Mixlib::CLI’s design :(



36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
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
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
# File 'lib/chef/knife/bootstrap_windows_base.rb', line 36

def self.included(includer)
  includer.class_eval do

    deps do
      require 'readline'
      require 'chef/json_compat'
    end

    option :chef_node_name,
      :short => "-N NAME",
      :long => "--node-name NAME",
      :description => "The Chef node name for your new node"

    option :prerelease,
      :long => "--prerelease",
      :description => "Install the pre-release chef gems"

    option :bootstrap_version,
      :long => "--bootstrap-version VERSION",
      :description => "The version of Chef to install",
      :proc => Proc.new { |v| Chef::Config[:knife][:bootstrap_version] = v }

    option :bootstrap_proxy,
      :long => "--bootstrap-proxy PROXY_URL",
      :description => "The proxy server for the node being bootstrapped",
      :proc => Proc.new { |p| Chef::Config[:knife][:bootstrap_proxy] = p }

    option :bootstrap_no_proxy,
      :long => "--bootstrap-no-proxy [NO_PROXY_URL|NO_PROXY_IP]",
      :description => "Do not proxy locations for the node being bootstrapped; this option is used internally by Opscode",
      :proc => Proc.new { |np| Chef::Config[:knife][:bootstrap_no_proxy] = np }

    option :bootstrap_install_command,
      :long        => "--bootstrap-install-command COMMANDS",
      :description => "Custom command to install chef-client",
      :proc        => Proc.new { |ic| Chef::Config[:knife][:bootstrap_install_command] = ic }

    # DEPR: Remove this option in Chef 13
    option :distro,
      :short => "-d DISTRO",
      :long => "--distro DISTRO",
      :description => "Bootstrap a distro using a template. [DEPRECATED] Use -t / --bootstrap-template option instead.",
      :proc        => Proc.new { |v|
        Chef::Log.warn("[DEPRECATED] -d / --distro option is deprecated. Use --bootstrap-template option instead.")
        v
      }

    option :bootstrap_template,
      :short => "-t TEMPLATE",
      :long => "--bootstrap-template TEMPLATE",
      :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."

    # DEPR: Remove this option in Chef 13
    option :template_file,
      :long => "--template-file TEMPLATE",
      :description => "Full path to location of template to use. [DEPRECATED] Use -t / --bootstrap-template option instead.",
      :proc        => Proc.new { |v|
        Chef::Log.warn("[DEPRECATED] --template-file option is deprecated. Use --bootstrap-template option instead.")
        v
      }

    option :run_list,
      :short => "-r RUN_LIST",
      :long => "--run-list RUN_LIST",
      :description => "Comma separated list of roles/recipes to apply",
      :proc => lambda { |o| o.split(",") },
      :default => []

    option :hint,
      :long => "--hint HINT_NAME[=HINT_FILE]",
      :description => "Specify Ohai Hint to be set on the bootstrap target. Use multiple --hint options to specify multiple hints.",
      :proc => Proc.new { |h|
        Chef::Config[:knife][:hints] ||= Hash.new
        name, path = h.split("=")
        Chef::Config[:knife][:hints][name] = path ? Chef::JSONCompat.parse(::File.read(path)) : Hash.new
      }

    option :first_boot_attributes,
      :short => "-j JSON_ATTRIBS",
      :long => "--json-attributes",
      :description => "A JSON string to be added to the first run of chef-client",
      :proc => lambda { |o| JSON.parse(o) },
      :default => nil

    option :first_boot_attributes_from_file,
      :long => "--json-attribute-file FILE",
      :description => "A JSON file to be used to the first run of chef-client",
      :proc => lambda { |o| Chef::JSONCompat.parse(File.read(o)) },
      :default => nil

    # Mismatch between option 'encrypted_data_bag_secret' and it's long value '--secret' is by design for compatibility
    option :encrypted_data_bag_secret,
      :short => "-s SECRET",
      :long  => "--secret ",
      :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.",
      :default => false

    # Mismatch between option 'encrypted_data_bag_secret_file' and it's long value '--secret-file' is by design for compatibility
    option :encrypted_data_bag_secret_file,
      :long => "--secret-file SECRET_FILE",
      :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."

    option :auth_timeout,
      :long => "--auth-timeout MINUTES",
      :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.",
      :default => 2

    option :node_ssl_verify_mode,
      :long        => "--node-ssl-verify-mode [peer|none]",
      :description => "Whether or not to verify the SSL cert for all HTTPS requests.",
      :proc        => Proc.new { |v|
        valid_values = ["none", "peer"]
        unless valid_values.include?(v)
          raise "Invalid value '#{v}' for --node-ssl-verify-mode. Valid values are: #{valid_values.join(", ")}"
        end
        v
      }

    option :node_verify_api_cert,
      :long        => "--[no-]node-verify-api-cert",
      :description => "Verify the SSL cert for HTTPS requests to the Chef server API.",
      :boolean     => true

    option :msi_url,
      :short => "-u URL",
      :long => "--msi-url URL",
      :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.",
      :default => ''

    option :install_as_service,
      :long => "--install-as-service",
      :description => "Install chef-client as a Windows service",
      :default => false

    option :bootstrap_vault_file,
    :long        => '--bootstrap-vault-file VAULT_FILE',
    :description => 'A JSON file with a list of vault(s) and item(s) to be updated'

    option :bootstrap_vault_json,
      :long        => '--bootstrap-vault-json VAULT_JSON',
      :description => 'A JSON string with the vault(s) and item(s) to be updated'

    option :bootstrap_vault_item,
      :long        => '--bootstrap-vault-item VAULT_ITEM',
      :description => 'A single vault and item to update as "vault:item"',
      :proc        => Proc.new { |i|
        (vault, item) = i.split(/:/)
        Chef::Config[:knife][:bootstrap_vault_item] ||= {}
        Chef::Config[:knife][:bootstrap_vault_item][vault] ||= []
        Chef::Config[:knife][:bootstrap_vault_item][vault].push(item)
        Chef::Config[:knife][:bootstrap_vault_item]
      }

    option :policy_name,
      :long         => "--policy-name POLICY_NAME",
      :description  => "Policyfile name to use (--policy-group must also be given)",
      :default      => nil

    option :policy_group,
      :long         => "--policy-group POLICY_GROUP",
      :description  => "Policy group name to use (--policy-name must also be given)",
      :default      => nil

    option :tags,
      :long => "--tags TAGS",
      :description => "Comma separated list of tags to apply to the node",
      :proc => lambda { |o| o.split(/[\s,]+/) },
      :default => []
  end
end

Instance Method Details

#bootstrap(proto = nil) ⇒ Object



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
314
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
# File 'lib/chef/knife/bootstrap_windows_base.rb', line 282

def bootstrap(proto=nil)
  if Chef::Config[:knife][:encrypted_data_bag_secret_file] || Chef::Config[:knife][:encrypted_data_bag_secret]
    warn_chef_config_secret_key
  end

  set_target_architecture

  # adding respond_to? so this works with pre 12.4 chef clients
  validate_options! if respond_to?(:validate_options!)

  @node_name = Array(@name_args).first
  # back compat--templates may use this setting:
  config[:server_name] = @node_name

  STDOUT.sync = STDERR.sync = true

  if Chef::VERSION.split('.').first.to_i == 11 && Chef::Config[:validation_key] && !File.exist?(File.expand_path(Chef::Config[:validation_key]))
    ui.error("Unable to find validation key. Please verify your configuration file for validation_key config value.")
    exit 1
  end

  if (defined?(chef_vault_handler) && chef_vault_handler.doing_chef_vault?) ||
      (Chef::Config[:validation_key] && !File.exist?(File.expand_path(Chef::Config[:validation_key])))

    unless locate_config_value(:chef_node_name)
      ui.error("You must pass a node name with -N when bootstrapping with user credentials")
      exit 1
    end

    client_builder.run

    if client_builder.respond_to?(:client)
      chef_vault_handler.run(client_builder.client)
    else
      chef_vault_handler.run(node_name: config[:chef_node_name])
    end

    bootstrap_context.client_pem = client_builder.client_path

  else
    ui.info("Doing old-style registration with the validation key at #{Chef::Config[:validation_key]}...")
    ui.info("Delete your validation key in order to use your user credentials instead")
    ui.info("")
  end

  wait_for_remote_response( config[:auth_timeout].to_i )

  ui.info("Bootstrapping Chef on #{ui.color(@node_name, :bold)}")
  # create a bootstrap.bat file on the node
  # we have to run the remote commands in 2047 char chunks
  create_bootstrap_bat_command do |command_chunk|
    render_command_result = run_command(command_chunk)
    unless render_command_result == 0
      ui.error("Batch render command returned #{render_command_result}")
      exit render_command_result
    end
  end

  # execute the bootstrap.bat file
  bootstrap_command_result = run_command(bootstrap_command)
  unless bootstrap_command_result == 0
    ui.error("Bootstrap command returned #{bootstrap_command_result}")
    exit bootstrap_command_result
  end

  # exit 0
  0
end

#bootstrap_contextObject



253
254
255
# File 'lib/chef/knife/bootstrap_windows_base.rb', line 253

def bootstrap_context
  @bootstrap_context ||= Knife::Core::WindowsBootstrapContext.new(config, config[:run_list], Chef::Config)
end

#bootstrap_templateObject



211
212
213
214
215
216
# File 'lib/chef/knife/bootstrap_windows_base.rb', line 211

def bootstrap_template
  # The order here is important. We want to check if we have the new Chef 12 option is set first.
  # Knife cloud plugins unfortunately all set a default option for the :distro so it should be at
  # the end.
  config[:bootstrap_template] || config[:template_file] || config[:distro] || default_bootstrap_template
end

#default_bootstrap_templateObject



207
208
209
# File 'lib/chef/knife/bootstrap_windows_base.rb', line 207

def default_bootstrap_template
  "windows-chef-client-msi"
end

#first_boot_attributesObject



272
273
274
# File 'lib/chef/knife/bootstrap_windows_base.rb', line 272

def first_boot_attributes
  config[:first_boot_attributes] || config[:first_boot_attributes_from_file] || {}
end

#load_correct_secretObject



257
258
259
260
261
262
263
264
265
266
267
268
269
270
# File 'lib/chef/knife/bootstrap_windows_base.rb', line 257

def load_correct_secret
  knife_secret_file = Chef::Config[:knife][:encrypted_data_bag_secret_file]
  knife_secret = Chef::Config[:knife][:encrypted_data_bag_secret]
  cli_secret_file = config[:encrypted_data_bag_secret_file]
  cli_secret = config[:encrypted_data_bag_secret]

  cli_secret_file = nil if cli_secret_file == knife_secret_file
  cli_secret = nil if cli_secret == knife_secret

  cli_secret_file = Chef::EncryptedDataBagItem.load_secret(cli_secret_file) if cli_secret_file != nil
  knife_secret_file = Chef::EncryptedDataBagItem.load_secret(knife_secret_file) if knife_secret_file != nil

  cli_secret_file || cli_secret || knife_secret_file || knife_secret
end

#load_template(template = nil) ⇒ Object

TODO: This should go away when CHEF-2193 is fixed



219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
# File 'lib/chef/knife/bootstrap_windows_base.rb', line 219

def load_template(template=nil)
  # Are we bootstrapping using an already shipped template?

  template = bootstrap_template

  # Use the template directly if it's a path to an actual file
  if File.exists?(template)
    Chef::Log.debug("Using the specified bootstrap template: #{File.dirname(template)}")
    return IO.read(template).chomp
  end

  # Otherwise search the template directories until we find the right one
  bootstrap_files = []
  bootstrap_files << File.join(File.dirname(__FILE__), 'bootstrap/templates', "#{template}.erb")
  bootstrap_files << File.join(Knife.chef_config_dir, "bootstrap", "#{template}.erb") if Chef::Knife.chef_config_dir
  ::Knife::Windows::PathHelper.all_homes('.chef', 'bootstrap', "#{template}.erb") { |p| bootstrap_files << p }
  bootstrap_files << Gem.find_files(File.join("chef","knife","bootstrap","#{template}.erb"))
  bootstrap_files.flatten!

  template = Array(bootstrap_files).find do |bootstrap_template|
    Chef::Log.debug("Looking for bootstrap template in #{File.dirname(bootstrap_template)}")
    ::File.exists?(bootstrap_template)
  end

  unless template
    ui.info("Can not find bootstrap definition for #{config[:distro]}")
    raise Errno::ENOENT
  end

  Chef::Log.debug("Found bootstrap template in #{File.dirname(template)}")

  IO.read(template).chomp
end

#render_template(template = nil) ⇒ Object



276
277
278
279
280
# File 'lib/chef/knife/bootstrap_windows_base.rb', line 276

def render_template(template=nil)
  config[:first_boot_attributes] = first_boot_attributes
  config[:secret] = load_correct_secret
  Erubis::Eruby.new(template).evaluate(bootstrap_context)
end