Class: Chef::Knife::VsphereVmClone

Inherits:
BaseVsphereCommand show all
Includes:
WinrmBase, CustomizationHelper
Defined in:
lib/chef/knife/vsphere_vm_clone.rb

Constant Summary collapse

AUTO_MAC =
'auto'
NO_IPS =
''

Instance Method Summary collapse

Methods included from CustomizationHelper

query_customization_succeeded, wait_for_sysprep

Methods inherited from BaseVsphereCommand

#choose_datastore, common_options, #conn_opts, #datacenter, #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_config, #get_password_from_stdin, #get_path_to_object, #get_vm, #get_vms, #linux?, #password, #tcp_test_port, #tcp_test_port_vm, #traverse_folders_for_computeresources, #traverse_folders_for_dc, #traverse_folders_for_vm, #traverse_folders_for_vms, #vim_connection, #windows?

Methods inherited from Chef::Knife

#log_verbose?

Instance Method Details

#bootstrap_common_params(bootstrap) ⇒ Object



769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
# File 'lib/chef/knife/vsphere_vm_clone.rb', line 769

def bootstrap_common_params(bootstrap)
  bootstrap.config[:run_list] = config[:run_list]
  bootstrap.config[:bootstrap_version] = get_config(:bootstrap_version)
  bootstrap.config[:distro] = get_config(:distro)
  bootstrap.config[:template_file] = get_config(:template_file)
  bootstrap.config[:environment] = get_config(:environment)
  bootstrap.config[:prerelease] = get_config(:prerelease)
  bootstrap.config[:first_boot_attributes] = get_config(:first_boot_attributes)
  bootstrap.config[:hint] = get_config(:hint)
  bootstrap.config[:chef_node_name] = get_config(:chef_node_name)
  bootstrap.config[:bootstrap_vault_file] = get_config(:bootstrap_vault_file)
  bootstrap.config[:bootstrap_vault_json] = get_config(:bootstrap_vault_json)
  bootstrap.config[:bootstrap_vault_item] = get_config(:bootstrap_vault_item)
  # may be needed for vpc mode
  bootstrap.config[:no_host_key_verify] = get_config(:no_host_key_verify)
  bootstrap.config[:node_ssl_verify_mode] = get_config(:node_ssl_verify_mode)
  bootstrap.config[:tags] = get_config(:tags)
  bootstrap
end

#bootstrap_for_nodeObject



811
812
813
814
815
816
817
818
819
820
821
822
823
824
# File 'lib/chef/knife/vsphere_vm_clone.rb', line 811

def bootstrap_for_node
  Chef::Knife::Bootstrap.load_deps
  bootstrap = Chef::Knife::Bootstrap.new
  bootstrap.name_args = [config[:fqdn]]
  bootstrap.config[:secret_file] = get_config(:secret_file)
  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[:use_sudo] = true unless get_config(:ssh_user) == 'root'
  bootstrap.config[:use_sudo_password] = true unless get_config(:ssh_user) == 'root'
  bootstrap.config[:log_level] = get_config(:log_level)
  bootstrap_common_params(bootstrap)
end

#bootstrap_for_windows_nodeObject



789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
# File 'lib/chef/knife/vsphere_vm_clone.rb', line 789

def bootstrap_for_windows_node
  Chef::Knife::Bootstrap.load_deps
  if get_config(:bootstrap_protocol) == 'winrm' || get_config(:bootstrap_protocol).nil?
    bootstrap = Chef::Knife::BootstrapWindowsWinrm.new
    bootstrap.name_args = [config[:fqdn]]
    bootstrap.config[:winrm_user] = get_config(:winrm_user)
    bootstrap.config[:winrm_password] = get_config(:winrm_password)
    bootstrap.config[:winrm_transport] = get_config(:winrm_transport)
    bootstrap.config[:winrm_port] = get_config(:winrm_port)
  elsif get_config(:bootstrap_protocol) == 'ssh'
    bootstrap = Chef::Knife::BootstrapWindowsSsh.new
    bootstrap.config[:ssh_user] = get_config(:ssh_user)
    bootstrap.config[:ssh_password] = get_config(:ssh_password)
    bootstrap.config[:ssh_port] = get_config(:ssh_port)
  else
    ui.error('Unsupported Bootstrapping Protocol. Supports : winrm, ssh')
    exit 1
  end
  bootstrap.config[:msi_url] = get_config(:bootstrap_msi_url)
  bootstrap_common_params(bootstrap)
end

#create_delta_disk(src_vm) ⇒ Object



455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
# File 'lib/chef/knife/vsphere_vm_clone.rb', line 455

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 do |new_disk|
            new_disk.backing = new_disk.backing.dup
            new_disk.backing.fileName = "[#{disk.backing.datastore.name}]"
            new_disk.backing.parent = disk.backing
          end
        }
      ]
    }
    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



699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
# File 'lib/chef/knife/vsphere_vm_clone.rb', line 699

def customization_plugin
  if @customization_plugin.nil?
    cplugin_path = get_config(:customization_plugin)
    if cplugin_path
      if File.exist? 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
        cplugin_data = get_config(:customization_plugin_data)
        if cplugin_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_available_hostsObject



479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
# File 'lib/chef/knife/vsphere_vm_clone.rb', line 479

def find_available_hosts
  hosts = traverse_folders_for_computeresources(datacenter.hostFolder)
  fatal_exit('No ComputeResource found - Use --resource-pool to specify a resource pool or a cluster') if hosts.empty?
  hosts.reject!(&:nil?)
  hosts.reject! { |host| host.host.all? { |h| h.runtime.inMaintenanceMode } }
  fatal_exit 'All hosts in maintenance mode!' if hosts.empty?
  if get_config(:datastore)
    hosts.reject! { |host| !host.datastore.include?(find_datastore(get_config(:datastore))) }
  end

  fatal_exit "No hosts have the requested Datastore available! #{get_config(:datastore)}" if hosts.empty?

  if get_config(:datastorecluster)
    hosts.reject! { |host| !host.datastore.include?(find_datastorecluster(get_config(:datastorecluster))) }
  end

  fatal_exit "No hosts have the requested DatastoreCluster available! #{get_config(:datastorecluster)}" if hosts.empty?

  if get_config(:customization_vlan)
    vlan_list = get_config(:customization_vlan).split(',')
    vlan_list.each do |network|
      hosts.reject! { |host| !host.network.include?(find_network(network)) }
    end
  end

  fatal_exit "No hosts have the requested Network available! #{get_config(:customization_vlan)}" if hosts.empty?
  hosts
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)


732
733
734
735
# File 'lib/chef/knife/vsphere_vm_clone.rb', line 732

def find_customization(name)
  csm = vim_connection.serviceContent.customizationSpecManager
  csm.GetCustomizationSpec(name: name)
end

#generate_adapter_map(ip = nil, gw = nil, mac = 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)


741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
# File 'lib/chef/knife/vsphere_vm_clone.rb', line 741

def generate_adapter_map(ip = nil, gw = nil, mac = 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.macAddress = mac if !mac.nil? && (mac != AUTO_MAC)
  adapter_map.adapter = settings
  adapter_map
end

#generate_clone_spec(src_config) ⇒ Object

Builds a CloneSpec



509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
# File 'lib/chef/knife/vsphere_vm_clone.rb', line 509

def generate_clone_spec(src_config)
  rspec = RbVmomi::VIM.VirtualMachineRelocateSpec

  rspec.pool = if get_config(:resource_pool)
                 find_pool(get_config(:resource_pool))
               else
                 hosts = find_available_hosts
                 hosts.first.resourcePool
               end

  rspec.diskMoveType = :moveChildMostDiskBacking if get_config(:linked_clone)

  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? || rspec.datastore.summary[:freeSpace] < store.summary[:freeSpace]
        rspec.datastore = store
      end
    end
  end

  rspec.transform = :sparse if get_config(:thin_provision)

  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: [])

  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

  mac_list = if get_config(:customization_macs) == AUTO_MAC
               [AUTO_MAC] * get_config(:customization_ips).split(',').length
             else
               get_config(:customization_macs).split(',')
             end

  if get_config(:customization_sw_uuid)
    unless get_config(:customization_vlan)
      abort('Must specify VLANs with --cvlan when specifying switch UUIDs with --sw-uuids')
    end
    swuuid_list = if get_config(:customization_sw_uuid) == 'auto'
                    ['auto'] * get_config(:customization_ips).split(',').length
                  else
                    get_config(:customization_sw_uuid).split(',').map { |swuuid| swuuid.gsub(/((\w+\s+){7})(\w+)\s+(.+)/, '\1\3-\4') }
                  end
  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] || abort("Can't find source network card to customize for vlan #{vlan_list[index]}")
      begin
        if get_config(:customization_sw_uuid) && (swuuid_list[index] != 'auto')
          switch_port = RbVmomi::VIM.DistributedVirtualSwitchPortConnection(
            switchUuid: swuuid_list[index], portgroupKey: network.key
          )
        else
          switch_port = RbVmomi::VIM.DistributedVirtualSwitchPortConnection(
            switchUuid: network.config.distributedVirtualSwitch.uuid, portgroupKey: network.key
          )
        end
        card.backing.port = switch_port
      rescue
        # not connected to a distibuted switch?
        card.backing = RbVmomi::VIM::VirtualEthernetCardNetworkBackingInfo(network: network, deviceName: network.name)
      end
      card.macAddress = mac_list[index] if get_config(:customization_macs) && mac_list[index] != AUTO_MAC
      dev_spec = RbVmomi::VIM.VirtualDeviceConfigSpec(device: card, operation: 'edit')
      clone_spec.config.deviceChange.push dev_spec
    end
  end

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

                csi.spec
              else
                global_ipset = RbVmomi::VIM.CustomizationGlobalIPSettings
                identity_settings = RbVmomi::VIM.CustomizationIdentitySettings
                RbVmomi::VIM.CustomizationSpec(globalIPSettings: global_ipset, identity: identity_settings)
              end

  if get_config(:disable_customization)
    clone_spec.customization = get_config(:customization_spec) ? cust_spec : nil
    return clone_spec
  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]
    cust_spec.nicSettingMap = config[:customization_ips].split(',').map.with_index { |cust_ip, index|
      generate_adapter_map(cust_ip, get_config(:customization_gw), mac_list[index])
    }
  end

  # TODO: why does the domain matter?
  use_ident = config[:customization_hostname] || get_config(:customization_domain) || cust_spec.identity.props.empty?

  # TODO: How could we not take this? Only if the identity were empty, but that's statically defined as empty above
  if use_ident
    hostname = config[:customization_hostname] || config[:vmname]

    if windows?(src_config)
      # We should get here with the customizations set, either by a plugin or a --cspec
      fatal_exit 'Windows clones need a customization identity. Try passing a --cspec or making a --cplugin' if cust_spec.identity.props.empty?

      identification = RbVmomi::VIM.CustomizationIdentification(
        joinWorkgroup: cust_spec.identity.identification.joinWorkgroup
      )
      license_file_print_data = RbVmomi::VIM.CustomizationLicenseFilePrintData(
        autoMode: cust_spec.identity.licenseFilePrintData.autoMode
      )

      user_data = RbVmomi::VIM.CustomizationUserData(
        fullName: cust_spec.identity.userData.fullName,
        orgName: cust_spec.identity.userData.orgName,
        productId: cust_spec.identity.userData.productId,
        computerName: RbVmomi::VIM.CustomizationFixedName(name: hostname)
      )

      gui_unattended = RbVmomi::VIM.CustomizationGuiUnattended(
        autoLogon: cust_spec.identity.guiUnattended.autoLogon,
        autoLogonCount: cust_spec.identity.guiUnattended.autoLogonCount,
        password: RbVmomi::VIM.CustomizationPassword(
          plainText: cust_spec.identity.guiUnattended.password.plainText,
          value: cust_spec.identity.guiUnattended.password.value
        ),
        timeZone: cust_spec.identity.guiUnattended.timeZone
      )
      runonce = RbVmomi::VIM.CustomizationGuiRunOnce(
        commandList: ['cust_spec.identity.guiUnattended.commandList']
      )
      ident = RbVmomi::VIM.CustomizationSysprep
      ident.guiRunOnce = runonce
      ident.guiUnattended = gui_unattended
      ident.identification = identification
      ident.licenseFilePrintData = license_file_print_data
      ident.userData = user_data
      cust_spec.identity = ident
    elsif linux?(src_config)
      ident = RbVmomi::VIM.CustomizationLinuxPrep
      ident.hostName = RbVmomi::VIM.CustomizationFixedName(name: hostname)

      ident.domain = if get_config(:customization_domain)
                       get_config(:customization_domain)
                     else
                       ''
                     end
      cust_spec.identity = ident
    else
      ui.error('Customization only supports Linux and Windows currently.')
      exit 1
    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
  clone_spec
end

#guest_address(vm) ⇒ Object



415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
# File 'lib/chef/knife/vsphere_vm_clone.rb', line 415

def guest_address(vm)
  puts 'Waiting for network interfaces to become available...'
  sleep 2 while vm.guest.net.empty? || !vm.guest.ipAddress
  ui.info "Found address #{vm.guest.ipAddress}" if log_verbose?
  config[:fqdn] = if config[:bootstrap_ipv4]
                    ipv4_address(vm)
                  elsif config[:fqdn]
                    get_config(:fqdn)
                  else
                    # Use the first IP which is not a link-local address.
                    # This is the closest thing to vm.guest.ipAddress but
                    # allows specifying a NIC.
                    vm.guest.net[bootstrap_nic_index].ipConfig.ipAddress.detect do |addr|
                      addr.origin != 'linklayer'
                    end.ipAddress
                  end
end

#ipv4_address(vm) ⇒ Object



406
407
408
409
410
411
412
413
# File 'lib/chef/knife/vsphere_vm_clone.rb', line 406

def ipv4_address(vm)
  puts 'Waiting for a valid IPv4 address...'
  # Multiple reboots occur during guest customization in which a link-local
  # address is assigned. As such, we need to wait until a routable IP address
  # becomes available. This is most commonly an issue with Windows instances.
  sleep 2 while vm.guest.net[bootstrap_nic_index].ipConfig.ipAddress.detect { |addr| IPAddr.new(addr.ipAddress).ipv4? }.origin == 'linklayer'
  vm.guest.net[bootstrap_nic_index].ipAddress.detect { |addr| IPAddr.new(addr).ipv4? }
end

#load_winrm_depsObject



905
906
907
908
909
910
911
# File 'lib/chef/knife/vsphere_vm_clone.rb', line 905

def load_winrm_deps
  require 'winrm'
  require 'chef/knife/winrm'
  require 'chef/knife/bootstrap_windows_winrm'
  require 'chef/knife/bootstrap_windows_ssh'
  require 'chef/knife/core/windows_bootstrap_context'
end

#runObject



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

def run
  $stdout.sync = true

  unless using_supplied_hostname? ^ using_random_hostname?
    show_usage
    fatal_exit('You must specify a virtual machine name OR use --random-vmname')
  end

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

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

  if get_config(:customization_macs) != AUTO_MAC && get_config(:customization_ips) == NO_IPS
    abort('Must specify IP numbers with --cips when specifying MAC addresses with --cmacs, can use "dhcp" as placeholder')
  end

  config[:chef_node_name] = vmname unless get_config(:chef_node_name)
  config[:vmname] = vmname

  vim = vim_connection
  vim.serviceContent.virtualDiskManager

  dc = datacenter

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

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

  create_delta_disk(src_vm) if get_config(:linked_clone)

  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}"

  pp clone_spec if log_verbose?

  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) || abort("VM could not be found in #{dest_folder}")
    customization_plugin.reconfig_vm(target_vm)
  end

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

  return unless get_config(:bootstrap)

  connect_host = guest_address(vm)
  Chef::Log.debug("Connect Host for Bootstrap: #{connect_host}")
  connect_port = get_config(:ssh_port)
  protocol = get_config(:bootstrap_protocol)
  if windows?(src_vm.config)
    protocol ||= 'winrm'
    # Set distro to windows-chef-client-msi
    config[:distro] = 'windows-chef-client-msi' if config[:distro].nil? || config[:distro] == 'chef-full'
    unless config[:disable_customization]
      # Wait for customization to complete
      puts 'Waiting for customization to complete...'
      CustomizationHelper.wait_for_sysprep(vm, vim, Integer(get_config(:sysprep_timeout)), 10)
      puts 'Customization Complete'
    end
    wait_for_access(connect_host, connect_port, protocol)
    ssh_override_winrm
    bootstrap_for_windows_node.run
  else
    protocol ||= 'ssh'
    wait_for_access(connect_host, connect_port, protocol)
    ssh_override_winrm
    bootstrap_for_node.run
  end
end

#ssh_override_winrmObject



826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
# File 'lib/chef/knife/vsphere_vm_clone.rb', line 826

def ssh_override_winrm
  # unchanged ssh_user and changed winrm_user, override ssh_user
  if get_config(:ssh_user).eql?(options[:ssh_user][:default]) &&
     !get_config(:winrm_user).eql?(options[:winrm_user][:default])
    config[:ssh_user] = get_config(:winrm_user)
  end

  # unchanged ssh_port and changed winrm_port, override ssh_port
  if get_config(:ssh_port).eql?(options[:ssh_port][:default]) &&
     !get_config(:winrm_port).eql?(options[:winrm_port][:default])
    config[:ssh_port] = get_config(:winrm_port)
  end

  # unset ssh_password and set winrm_password, override ssh_password
  if get_config(:ssh_password).nil? &&
     !get_config(:winrm_password).nil?
    config[:ssh_password] = get_config(:winrm_password)
  end

  # unset identity_file and set kerberos_keytab_file, override identity_file
  return unless get_config(:identity_file).nil? && !get_config(:kerberos_keytab_file).nil?

  config[:identity_file] = get_config(:kerberos_keytab_file)
end

#tcp_test_ssh(hostname, ssh_port) ⇒ Object



851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
# File 'lib/chef/knife/vsphere_vm_clone.rb', line 851

def tcp_test_ssh(hostname, ssh_port)
  tcp_socket = TCPSocket.new(hostname, ssh_port)
  readable = IO.select([tcp_socket], nil, nil, 5)
  if readable
    ssh_banner = tcp_socket.gets
    if ssh_banner.nil? || ssh_banner.empty?
      false
    else
      Chef::Log.debug("sshd accepting connections on #{hostname}, banner is #{ssh_banner}")
      yield
      true
    end
  else
    false
  end
rescue SocketError, Errno::ECONNREFUSED, Errno::EHOSTUNREACH, Errno::ENETUNREACH, IOError
  Chef::Log.debug("ssh failed to connect: #{hostname}")
  sleep 2
  false
rescue Errno::EPERM, Errno::ETIMEDOUT
  Chef::Log.debug("ssh timed out: #{hostname}")
  false
rescue Errno::ECONNRESET
  Chef::Log.debug("ssh reset its connection: #{hostname}")
  sleep 2
  false
ensure
  tcp_socket && tcp_socket.close
end

#tcp_test_winrm(hostname, port) ⇒ Object



881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
# File 'lib/chef/knife/vsphere_vm_clone.rb', line 881

def tcp_test_winrm(hostname, port)
  tcp_socket = TCPSocket.new(hostname, port)
  yield
  true
rescue SocketError
  sleep 2
  false
rescue Errno::ETIMEDOUT
  false
rescue Errno::EPERM
  false
rescue Errno::ECONNREFUSED
  sleep 2
  false
rescue Errno::EHOSTUNREACH
  sleep 2
  false
rescue Errno::ENETUNREACH
  sleep 2
  false
ensure
  tcp_socket && tcp_socket.close
end

#wait_for_access(connect_host, connect_port, protocol) ⇒ Object



433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
# File 'lib/chef/knife/vsphere_vm_clone.rb', line 433

def wait_for_access(connect_host, connect_port, protocol)
  if protocol == 'winrm'
    load_winrm_deps
    if get_config(:winrm_transport) == 'ssl' && get_config(:winrm_port) == '5985'
      config[:winrm_port] = '5986'
    end
    connect_port = get_config(:winrm_port)
    print "\n#{ui.color("Waiting for winrm access to become available on #{connect_host}:#{connect_port}", :magenta)}"
    print('.') until tcp_test_winrm(connect_host, connect_port) do
      sleep 10
      puts('done')
    end
  else
    print "\n#{ui.color("Waiting for sshd access to become available on #{connect_host}:#{connect_port}", :magenta)}"
    print('.') until tcp_test_ssh(connect_host, connect_port) do
      sleep 10
      puts('done')
    end
  end
  connect_port
end