Class: Chef::Knife::VsphereVmClone

Inherits:
BaseVsphereCommand show all
Defined in:
lib/chef/knife/vsphere_vm_clone.rb

Overview

Clone an existing template into a new VM, optionally applying a customization specification. usage: knife vsphere vm clone NewNode UbuntuTemplate –cspec StaticSpec \

--cips 192.168.0.99/24,192.168.1.99/24 \
--chostname NODENAME --cdomain NODEDOMAIN

Instance Method Summary collapse

Methods inherited from BaseVsphereCommand

#choose_datastore, #fatal_exit, #find_all_in_folder, #find_datastore, #find_datastorecluster, #find_datastores_regex, #find_device, #find_folder, #find_in_folder, #find_network, #find_pool, get_common_options, #get_config, #get_datacenter, #get_password, #get_path_to_object, #get_vim_connection, #get_vm, #get_vms, #tcp_test_port, #tcp_test_port_vm, #traverse_folders_for_dc, #traverse_folders_for_vm, #traverse_folders_for_vms

Instance Method Details

#bootstrap_for_nodeObject



534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
# File 'lib/chef/knife/vsphere_vm_clone.rb', line 534

def bootstrap_for_node()
  Chef::Knife::Bootstrap.load_deps
  bootstrap = Chef::Knife::Bootstrap.new
  bootstrap.name_args = [config[:fqdn]]
  bootstrap.config[:run_list] = get_config(:run_list).split(/[\s,]+/)
  bootstrap.config[:secret_file] = get_config(:secret_file)
  bootstrap.config[:hint] = get_config(:hint)
  bootstrap.config[:ssh_user] = get_config(:ssh_user)
  bootstrap.config[:ssh_password] = get_config(:ssh_password)
  bootstrap.config[:ssh_port] = get_config(:ssh_port)
  bootstrap.config[:identity_file] = get_config(:identity_file)
  bootstrap.config[:chef_node_name] = get_config(:chef_node_name)
  bootstrap.config[:prerelease] = get_config(:prerelease)
  bootstrap.config[:bootstrap_version] = get_config(:bootstrap_version)
  bootstrap.config[:distro] = get_config(:distro)
  bootstrap.config[:use_sudo] = true unless get_config(:ssh_user) == 'root'
  bootstrap.config[:template_file] = get_config(:template_file)
  bootstrap.config[:environment] = get_config(:environment)
  bootstrap.config[:first_boot_attributes] = get_config(:first_boot_attributes)
  bootstrap.config[:log_level] = get_config(:log_level)
  # may be needed for vpc_mode
  bootstrap.config[:no_host_key_verify] = get_config(:no_host_key_verify)
  bootstrap
end

#create_delta_disk(src_vm) ⇒ Object



302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
# File 'lib/chef/knife/vsphere_vm_clone.rb', line 302

def create_delta_disk(src_vm)
  disks = src_vm.config.hardware.device.grep(RbVmomi::VIM::VirtualDisk)
  disks.select { |disk| disk.backing.parent == nil }.each do |disk|
    spec = {
        :deviceChange => [
            {
                :operation => :remove,
                :device => disk
            },
            {
                :operation => :add,
                :fileOperation => :create,
                :device => disk.dup.tap { |new_disk|
                  new_disk.backing = new_disk.backing.dup
                  new_disk.backing.fileName = "[#{disk.backing.datastore.name}]"
                  new_disk.backing.parent = disk.backing
                },
            }
        ]
    }
    src_vm.ReconfigVM_Task(:spec => spec).wait_for_completion
    end
end

#customization_pluginKnifeVspherePlugin

Loads the customization plugin if one was specified

Returns:

  • (KnifeVspherePlugin)

    the loaded and initialized plugin or nil



466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
# File 'lib/chef/knife/vsphere_vm_clone.rb', line 466

def customization_plugin
  if @customization_plugin.nil?
    if cplugin_path = get_config(:customization_plugin)
      if File.exists? cplugin_path
        require cplugin_path
      else
        abort "Customization plugin could not be found at #{cplugin_path}"
      end

      if Object.const_defined? 'KnifeVspherePlugin'
        @customization_plugin = Object.const_get('KnifeVspherePlugin').new
        if cplugin_data = get_config(:customization_plugin_data)
          if @customization_plugin.respond_to?(:data=)
            @customization_plugin.data = cplugin_data
          else
            abort "Customization plugin has no :data= accessor to receive the --cplugin-data argument.  Define both or neither."
          end
        end
      else
        abort "KnifeVspherePlugin class is not defined in #{cplugin_path}"
      end
    end
  end

  @customization_plugin
end

#find_customization(name) ⇒ RbVmomi::VIM::CustomizationSpecItem

Retrieves a CustomizationSpecItem that matches the supplied name

Parameters:

  • vim (Connection)

    VI Connection to use

  • name (String)

    name of customization

Returns:

  • (RbVmomi::VIM::CustomizationSpecItem)


497
498
499
500
# File 'lib/chef/knife/vsphere_vm_clone.rb', line 497

def find_customization(name)
  csm = config[:vim].serviceContent.customizationSpecManager
  csm.GetCustomizationSpec(:name => name)
end

#generate_adapter_map(ip = nil, gw = nil, dns1 = nil, dns2 = nil, domain = nil) ⇒ RbVmomi::VIM::CustomizationIPSettings

Generates a CustomizationAdapterMapping (currently only single IPv4 address) object

Parameters:

  • ip (String) (defaults to: nil)

    Any static IP address to use, or “dhcp” for DHCP

  • gw (String) (defaults to: nil)

    If static, the gateway for the interface, otherwise network address + 1 will be used

Returns:

  • (RbVmomi::VIM::CustomizationIPSettings)


506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
# File 'lib/chef/knife/vsphere_vm_clone.rb', line 506

def generate_adapter_map (ip=nil, gw=nil, dns1=nil, dns2=nil, domain=nil)

  settings = RbVmomi::VIM.CustomizationIPSettings

  if ip.nil? || ip.downcase == "dhcp"
    settings.ip = RbVmomi::VIM::CustomizationDhcpIpGenerator.new
  else
    cidr_ip = NetAddr::CIDR.create(ip)
    settings.ip = RbVmomi::VIM::CustomizationFixedIp(:ipAddress => cidr_ip.ip)
    settings.subnetMask = cidr_ip.netmask_ext

    # TODO - want to confirm gw/ip are in same subnet?
    # Only set gateway on first IP.
    if config[:customization_ips].split(',').first == ip
      if gw.nil?
        settings.gateway = [cidr_ip.network(:Objectify => true).next_ip]
      else
        gw_cidr = NetAddr::CIDR.create(gw)
        settings.gateway = [gw_cidr.ip]
      end
    end
  end

  adapter_map = RbVmomi::VIM.CustomizationAdapterMapping
  adapter_map.adapter = settings
  adapter_map
end

#generate_clone_spec(src_config) ⇒ Object

Builds a CloneSpec



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
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
# File 'lib/chef/knife/vsphere_vm_clone.rb', line 327

def generate_clone_spec (src_config)
  rspec = nil
  if get_config(:resource_pool)
    rspec = RbVmomi::VIM.VirtualMachineRelocateSpec(:pool => find_pool(get_config(:resource_pool)))
  else
    dc = get_datacenter
    hosts = find_all_in_folder(dc.hostFolder, RbVmomi::VIM::ComputeResource)
    rp = hosts.first.resourcePool
    rspec = RbVmomi::VIM.VirtualMachineRelocateSpec(:pool => rp)
  end

  if get_config(:linked_clone)
    rspec = RbVmomi::VIM.VirtualMachineRelocateSpec(:diskMoveType => :moveChildMostDiskBacking)
  end

  if get_config(:datastore) && get_config(:datastorecluster)
    abort "Please select either datastore or datastorecluster"
  end

  if get_config(:datastore)
    rspec.datastore = find_datastore(get_config(:datastore))
  end

  if get_config(:datastorecluster)
    dsc = find_datastorecluster(get_config(:datastorecluster))

    dsc.childEntity.each do |store|
      if (rspec.datastore == nil or rspec.datastore.summary[:freeSpace] < store.summary[:freeSpace])
        rspec.datastore = store
      end
    end
  end

  if get_config(:thin_provision)
    rspec = RbVmomi::VIM.VirtualMachineRelocateSpec(:transform => :sparse, :pool => find_pool(get_config(:resource_pool)))
  end

  is_template = !get_config(:mark_as_template).nil?
  clone_spec = RbVmomi::VIM.VirtualMachineCloneSpec(:location => rspec, :powerOn => false,:template => is_template)

  clone_spec.config = RbVmomi::VIM.VirtualMachineConfigSpec(:deviceChange => Array.new)

  if get_config(:annotation)
    clone_spec.config.annotation = get_config(:annotation)
  end

  if get_config(:customization_cpucount)
    clone_spec.config.numCPUs = get_config(:customization_cpucount)
  end

  if get_config(:customization_memory)
    clone_spec.config.memoryMB = Integer(get_config(:customization_memory)) * 1024
  end

  if get_config(:customization_vlan)
    vlan_list = get_config(:customization_vlan).split(',')
    networks = vlan_list.map { |vlan| find_network(vlan) }

    cards = src_config.hardware.device.grep(RbVmomi::VIM::VirtualEthernetCard)

    networks.each_with_index do |network, index|
      card = cards[index] or abort "Can't find source network card to customize for vlan #{vlan_list[index]}"
      begin
        switch_port = RbVmomi::VIM.DistributedVirtualSwitchPortConnection(:switchUuid => network.config.distributedVirtualSwitch.uuid, :portgroupKey => network.key)
        card.backing.port = switch_port
      rescue
        # not connected to a distibuted switch?
        card.backing = RbVmomi::VIM::VirtualEthernetCardNetworkBackingInfo(:network => network, :deviceName => network.name)
      end
      dev_spec = RbVmomi::VIM.VirtualDeviceConfigSpec(:device => card, :operation => "edit")
      clone_spec.config.deviceChange.push dev_spec
    end
  end

  if get_config(:customization_spec)
    csi = find_customization(get_config(:customization_spec)) or
        fatal_exit("failed to find customization specification named #{get_config(:customization_spec)}")

    cust_spec = csi.spec
  else
    global_ipset = RbVmomi::VIM.CustomizationGlobalIPSettings
    cust_spec = RbVmomi::VIM.CustomizationSpec(:globalIPSettings => global_ipset)
  end

  if get_config(:customization_dns_ips)
    cust_spec.globalIPSettings.dnsServerList = get_config(:customization_dns_ips).split(',')
  end

  if get_config(:customization_dns_suffixes)
    cust_spec.globalIPSettings.dnsSuffixList = get_config(:customization_dns_suffixes).split(',')
  end

  if config[:customization_ips]
    if get_config(:customization_gw)
      cust_spec.nicSettingMap = config[:customization_ips].split(',').map { |i| generate_adapter_map(i, get_config(:customization_gw)) }
    else
      cust_spec.nicSettingMap = config[:customization_ips].split(',').map { |i| generate_adapter_map(i) }
    end
  end

  unless get_config(:disable_customization)
    use_ident = !config[:customization_hostname].nil? || !get_config(:customization_domain).nil? || cust_spec.identity.nil?

    if use_ident
      hostname = if config[:customization_hostname]
        config[:customization_hostname]
      else
        config[:vmname]
      end

      if src_config.guestId.downcase.include?("windows")
        if cust_spec.identity.nil?
          fatal_exit("Please provide Windows Guest Customization")
        else
          cust_spec.identity.userData.computerName = RbVmomi::VIM.CustomizationFixedName(:name => hostname)
        end
      else
        ident = RbVmomi::VIM.CustomizationLinuxPrep
        ident.hostName = RbVmomi::VIM.CustomizationFixedName(:name => hostname)
        if get_config(:customization_domain)
          ident.domain = get_config(:customization_domain)
        else
          ident.domain = ''
        end
        cust_spec.identity = ident
      end
    end

    clone_spec.customization = cust_spec

    if customization_plugin && customization_plugin.respond_to?(:customize_clone_spec)
      clone_spec = customization_plugin.customize_clone_spec(src_config, clone_spec)
    end
  end
  clone_spec
end

#runObject



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
# File 'lib/chef/knife/vsphere_vm_clone.rb', line 234

def run
  $stdout.sync = true

  vmname = @name_args[0]
  if vmname.nil?
    show_usage
    fatal_exit("You must specify a virtual machine name")
  end
  config[:chef_node_name] = vmname unless config[:chef_node_name]
  config[:vmname] = vmname

  if get_config(:bootstrap) && get_config(:distro) && !@@chef_config_dir
    fatal_exit("Can't find .chef for bootstrap files. chdir to a location with a .chef directory and try again")
  end

  vim = get_vim_connection
  vdm = vim.serviceContent.virtualDiskManager

  dc = get_datacenter

  src_folder = find_folder(get_config(:folder)) || dc.vmFolder

  abort "--template or knife[:source_vm] must be specified" unless config[:source_vm]

  src_vm = find_in_folder(src_folder, RbVmomi::VIM::VirtualMachine, config[:source_vm]) or
      abort "VM/Template not found"

  if get_config(:linked_clone)
    create_delta_disk(src_vm)
  end

  clone_spec = generate_clone_spec(src_vm.config)

  cust_folder = config[:dest_folder] || get_config(:folder)

  dest_folder = cust_folder.nil? ? src_vm.vmFolder : find_folder(cust_folder)

  task = src_vm.CloneVM_Task(:folder => dest_folder, :name => vmname, :spec => clone_spec)
  puts "Cloning template #{config[:source_vm]} to new VM #{vmname}"
  task.wait_for_completion
  puts "Finished creating virtual machine #{vmname}"

  if customization_plugin && customization_plugin.respond_to?(:reconfig_vm)
    target_vm = find_in_folder(dest_folder, RbVmomi::VIM::VirtualMachine, vmname) or abort "VM could not be found in #{dest_folder}"
    customization_plugin.reconfig_vm(target_vm)
  end

  if !get_config(:mark_as_template)
    if get_config(:power) || get_config(:bootstrap)
      vm = find_in_folder(dest_folder, RbVmomi::VIM::VirtualMachine, vmname) or
          fatal_exit("VM #{vmname} not found")
      vm.PowerOnVM_Task.wait_for_completion
      puts "Powered on virtual machine #{vmname}"
    end


    if get_config(:bootstrap)
      sleep 2 until vm.guest.ipAddress
      config[:fqdn] = vm.guest.ipAddress unless config[:fqdn]
      print "Waiting for sshd..."
      print "." until tcp_test_ssh(config[:fqdn])
      puts "done"

      bootstrap_for_node.run
    end
  end
end

#tcp_test_ssh(hostname) ⇒ Object



559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
# File 'lib/chef/knife/vsphere_vm_clone.rb', line 559

def tcp_test_ssh(hostname)
  tcp_socket = TCPSocket.new(hostname, get_config(:ssh_port))
  readable = IO.select([tcp_socket], nil, nil, 5)
  if readable
    Chef::Log.debug("sshd accepting connections on #{hostname}, banner is #{tcp_socket.gets}")
    true
  else
    false
  end
rescue Errno::ETIMEDOUT
  false
rescue Errno::EPERM
  false
rescue Errno::ECONNREFUSED
  sleep 2
  false
rescue Errno::EHOSTUNREACH, Errno::ENETUNREACH
  sleep 2
  false
ensure
  tcp_socket && tcp_socket.close
end