
    Vh                    4   d dl mZmZmZ eZdZdZdZd dl	Z	d dl
Z
d dlZ	 d dlmZmZ d dlmZ d dlmZ d d	lmZmZ d d
lmZmZmZmZmZmZmZmZm Z m!Z!m"Z" d dl#m$Z$ d dl%m&Z& d dl'm(Z(  G d de      Z) G d de      Z*d Z+e,dk(  r e+        yy# e$ r Y nw xY w)    )absolute_importdivisionprint_functionaƈ  
---
module: vmware_guest
short_description: Manages virtual machines in vCenter
description: >
   This module can be used to create new virtual machines from templates or other virtual machines,
   manage power state of virtual machine such as power on, power off, suspend, shutdown, reboot, restart etc.,
   modify various virtual machine components like network, disk, customization etc.,
   rename a virtual machine and remove a virtual machine with associated components.
author:
- Loic Blot (@nerzhul) <loic.blot@unix-experience.fr>
- Philippe Dellaert (@pdellaert) <philippe@dellaert.org>
- Abhijeet Kasurde (@Akasurde) <akasurde@redhat.com>
notes:
    - Please make sure that the user used for M(community.vmware.vmware_guest) has the correct level of privileges.
    - For example, following is the list of minimum privileges required by users to create virtual machines.
    - "   DataStore > Allocate Space"
    - "   Virtual Machine > Configuration > Add New Disk"
    - "   Virtual Machine > Configuration > Add or Remove Device"
    - "   Virtual Machine > Inventory > Create New"
    - "   Network > Assign Network"
    - "   Resource > Assign Virtual Machine to Resource Pool"
    - "Module may require additional privileges as well, which may be required for gathering facts - e.g. ESXi configurations."
    - Use SCSI disks instead of IDE when you want to expand online disks by specifying a SCSI controller.
    - Uses SysPrep for Windows VM (depends on 'guest_id' parameter match 'win') with PyVmomi.
    - In order to change the VM's parameters (e.g. number of CPUs), the VM must be powered off unless the hot-add
      support is enabled and the O(state=present) must be used to apply the changes.
    - "For additional information please visit Ansible VMware community wiki - U(https://github.com/ansible/community/wiki/VMware)."
options:
  state:
    description:
    - Specify the state the virtual machine should be in.
    - If V(present) and virtual machine exists, ensure the virtual machine configurations conforms to task arguments.
    - If V(absent) and virtual machine exists, then the specified virtual machine is removed with it's associated components.
    - If set to one of V(poweredon), V(powered-on), V(poweredoff), V(powered-off),
      V(present), V(restarted), V(suspended) and virtual machine does not exists, virtual machine is deployed with the given parameters.
    - If set to V(poweredon) or V(powered-on) and virtual machine exists with powerstate other than powered on,
      then the specified virtual machine is powered on.
    - If set to V(poweredoff) or V(powered-off) and virtual machine exists with powerstate other than powered off,
      then the specified virtual machine is powered off.
    - If set to V(restarted) and virtual machine exists, then the virtual machine is restarted.
    - If set to V(suspended) and virtual machine exists, then the virtual machine is set to suspended mode.
    - If set to V(shutdownguest) or V(shutdown-guest) and virtual machine exists, then the virtual machine is shutdown.
    - If set to V(rebootguest) or V(reboot-guest) and virtual machine exists, then the virtual machine is rebooted.
    default: present
    type: str
    choices: [ absent, poweredon, powered-on, poweredoff, powered-off, present, rebootguest, reboot-guest, restarted, suspended, shutdownguest, shutdown-guest]
  name:
    description:
    - Name of the virtual machine to work with.
    - Virtual machine names in vCenter are not necessarily unique, which may be problematic, see O(name_match).
    - If multiple virtual machines with same name exists, then O(folder) is required parameter to
      identify uniqueness of the virtual machine.
    - This parameter is required, if O(state=poweredon), O(state=powered-on), O(state=poweredoff), O(state=powered-off),
      O(state=present), O(state=restarted), O(state=suspended) and virtual machine does not exists.
    type: str
  name_match:
    description:
    - If multiple virtual machines matching the name, use the first or last found.
    default: 'first'
    choices: [ 'first', 'last' ]
    type: str
  uuid:
    description:
    - UUID of the virtual machine to manage if known, this is VMware's unique identifier.
    - This is required if O(name) is not supplied.
    - If virtual machine does not exists, then this parameter is ignored.
    - Please note that a supplied UUID will be ignored on virtual machine creation, as VMware creates the UUID internally.
    type: str
  use_instance_uuid:
    description:
    - Whether to use the VMware instance UUID rather than the BIOS UUID.
    default: false
    type: bool
  template:
    description:
    - Template or existing virtual machine used to create new virtual machine.
    - If this value is not set, virtual machine is created without using a template.
    - If the virtual machine already exists, this parameter will be ignored.
    - From version 2.8 onwards, absolute path to virtual machine or template can be used.
    aliases: [ 'template_src' ]
    type: str
  is_template:
    description:
    - Flag the instance as a template.
    - This will mark the given virtual machine as template.
    - Note, this may need to be done in a dedicated task invocation that is not making
      any other changes. For example, user cannot change the state from powered-on to
      powered-off AND save as template in the same task.
    - See M(community.vmware.vmware_guest) source for more details.
    default: false
    type: bool
  folder:
    description:
    - Destination folder, absolute path to find an existing guest or create the new guest.
    - "The folder should include the datacenter. ESXi's datacenter is ha-datacenter."
    - 'If multiple machines are found with same name, this parameter is used to identify'
    - 'uniqueness of the virtual machine.'
    - 'Examples:'
    - '   folder: /ha-datacenter/vm'
    - '   folder: ha-datacenter/vm'
    - '   folder: /datacenter1/vm'
    - '   folder: datacenter1/vm'
    - '   folder: /datacenter1/vm/folder1'
    - '   folder: datacenter1/vm/folder1'
    - '   folder: /folder1/datacenter1/vm'
    - '   folder: folder1/datacenter1/vm'
    - '   folder: /folder1/datacenter1/vm/folder2'
    type: str
  hardware:
    type: dict
    default: {}
    description:
    - "Manage virtual machine's hardware attributes."
    suboptions:
        hotadd_cpu:
            type: bool
            description: Allow virtual CPUs to be added while the virtual machine is running.
        hotremove_cpu:
            type: bool
            description: Allow virtual CPUs to be removed while the virtual machine is running.
        hotadd_memory:
            type: bool
            description: Allow memory to be added while the virtual machine is running.
        memory_mb:
            type: int
            description: Amount of memory in MB.
        num_cpus:
            type: int
            description:
            - Number of CPUs.
            - Must be a multiple of O(hardware.num_cpu_cores_per_socket).
            - For example, to create a VM with 2 sockets of 4 cores, specify O(hardware.num_cpus) as 8 and O(hardware.num_cpu_cores_per_socket) as 4.
        num_cpu_cores_per_socket:
            type: int
            description: Number of Cores Per Socket.
        cpu_shares_level:
            type: str
            choices: [ 'low', 'normal', 'high', 'custom' ]
            description:
            - The allocation level of CPU resources for the virtual machine.
            version_added: '3.2.0'
        cpu_shares:
            type: int
            description:
            - The number of shares of CPU allocated to this virtual machine
            - cpu_shares_level will automatically be set to 'custom'
            version_added: '3.2.0'
        vpmc_enabled:
            version_added: '3.2.0'
            type: bool
            description: Enable virtual CPU Performance Counters.
        scsi:
            type: str
            description:
            - Valid values are V(buslogic), V(lsilogic), V(lsilogicsas) and V(paravirtual).
            - V(paravirtual) is default.
            choices: [ 'buslogic', 'lsilogic', 'lsilogicsas', 'paravirtual' ]
        secure_boot:
            type: bool
            description: Whether to enable or disable (U)EFI secure boot.
        memory_reservation_lock:
            type: bool
            description:
            - If set V(true), memory resource reservation for the virtual machine.
        max_connections:
            type: int
            description:
            - Maximum number of active remote display connections for the virtual machines.
        mem_limit:
            type: int
            description:
            - The memory utilization of a virtual machine will not exceed this limit.
            - Unit is MB.
        mem_reservation:
            type: int
            description: The amount of memory resource that is guaranteed available to the virtual machine.
            aliases: [ 'memory_reservation' ]
        mem_shares_level:
            type: str
            description:
            - The allocation level of memory resources for the virtual machine.
            choices: [ 'low', 'normal', 'high', 'custom' ]
            version_added: '3.2.0'
        mem_shares:
            type: int
            description:
            - The number of shares of memory allocated to this virtual machine
            - mem_shares_level will automatically be set to 'custom'
            version_added: '3.2.0'
        cpu_limit:
            type: int
            description:
            - The CPU utilization of a virtual machine will not exceed this limit.
            - Unit is MHz.
        cpu_reservation:
            type: int
            description: The amount of CPU resource that is guaranteed available to the virtual machine.
        version:
            type: str
            description:
            - The Virtual machine hardware versions.
            - Default is 10 (ESXi 5.5 and onwards).
            - If set to V(latest), the specified virtual machine will be upgraded to the most current hardware version supported on the host.
            - Please check VMware documentation for correct virtual machine hardware version.
            - Incorrect hardware version may lead to failure in deployment. If hardware version is already equal to the given.
        boot_firmware:
            type: str
            description: Choose which firmware should be used to boot the virtual machine.
            choices: [ 'bios', 'efi' ]
        nested_virt:
            type: bool
            description:
            - Enable nested virtualization.
        virt_based_security:
            type: bool
            description:
            - Enable Virtualization Based Security feature for Windows on ESXi 6.7 and later, from hardware version 14.
            - Supported Guest OS are Windows 10 64 bit, Windows Server 2016, Windows Server 2019 and later.
            - The firmware of virtual machine must be EFI and secure boot must be enabled.
            - Virtualization Based Security depends on nested virtualization and Intel Virtualization Technology for Directed I/O.
            - Deploy on unsupported ESXi, hardware version or firmware may lead to failure or deployed VM with unexpected configurations.
        iommu:
            type: bool
            description: Flag to specify if I/O MMU is enabled for this virtual machine.
  encryption:
    type: dict
    default: {}
    description:
    - Manage virtual machine encryption settings
    version_added: '3.9.0'
    suboptions:
        encrypted_vmotion:
            type: str
            description: Controls encryption for live migrations with vmotion
            choices: ['disabled', 'opportunistic', 'required']
        encrypted_ft:
            type: str
            description: Controls encryption for fault tolerance replication
            choices: ['disabled', 'opportunistic', 'required']
  guest_id:
    type: str
    description:
    - Set the guest ID.
    - This field is required when creating a virtual machine, not required when creating from the template.
    - >
         Valid values are referenced here:
         U(https://code.vmware.com/apis/358/doc/vim.vm.GuestOsDescriptor.GuestOsIdentifier.html)
  disk:
    description:
    - A list of disks to add.
    - Shrinking disks is not supported.
    - Removing existing disks of the virtual machine is not supported.
    - 'Attributes O(disk[].controller_type), O(disk[].controller_number), O(disk[].unit_number) are used to configure multiple types of disk
      controllers and disks for creating or reconfiguring virtual machine.'
    type: list
    default: []
    elements: dict
    suboptions:
        size:
            description:
            - Disk storage size.
            - Please specify storage unit like [kb, mb, gb, tb].
            type: str
        size_kb:
            description: Disk storage size in kb.
            type: int
        size_mb:
            description: Disk storage size in mb.
            type: int
        size_gb:
            description: Disk storage size in gb.
            type: int
        size_tb:
            description: Disk storage size in tb.
            type: int
        type:
            description:
            - Type of disk.
            - If not specified, disk type is inherited from the source VM or template when cloned and thick disk, no eagerzero otherwise.
            type: str
            choices: [ 'thin', 'thick', 'eagerzeroedthick' ]
        datastore:
            type: str
            description:
            - The name of datastore which will be used for the disk.
            - If O(disk[].autoselect_datastore) is set to True, will select the less used datastore whose name contains this "disk.datastore" string.
        filename:
            type: str
            description:
            - Existing disk image to be used.
            - Filename must already exist on the datastore.
            - Specify filename string in C([datastore_name] path/to/file.vmdk) format.
        autoselect_datastore:
            type: bool
            description:
            - Select the less used datastore.
            - O(disk[].datastore) and O(disk[].autoselect_datastore) will not be used if O(datastore) is specified outside this O(disk[]) configuration.
        disk_mode:
            type: str
            choices: ['persistent', 'independent_persistent', 'independent_nonpersistent']
            description:
            - Type of disk mode.
            - If V(persistent) specified, changes are immediately and permanently written to the virtual disk. This is default.
            - If V(independent_persistent) specified, same as persistent, but not affected by snapshots.
            - If V(independent_nonpersistent) specified, changes to virtual disk are made to a redo log and discarded at power off,
              but not affected by snapshots.
        controller_type:
            type: str
            choices: ['buslogic', 'lsilogic', 'lsilogicsas', 'paravirtual', 'sata', 'nvme']
            description:
            - Type of disk controller.
              Set this type on not supported ESXi or VM hardware version will lead to failure in deployment.
            - When set to V(sata), please make sure O(disk[].unit_number) is correct and not used by SATA CDROMs.
            - If set to V(sata) type, please make sure O(disk[].controller_number) and O(disk[].unit_number) are set correctly when O(cdrom=sata).
        controller_number:
            type: int
            choices: [0, 1, 2, 3]
            description:
            - Disk controller bus number.
            - The maximum number of same type controller is 4 per VM.
        unit_number:
            type: int
            description:
            - Disk Unit Number.
            - Valid value range from 0 to 15 for SCSI controller, except 7.
            - Valid value range from 0 to 14 for NVME controller.
            - Valid value range from 0 to 29 for SATA controller.
            - O(disk[].controller_type), O(disk[].controller_number) and O(disk[].unit_number) are required when creating or reconfiguring VMs
              with multiple types of disk controllers and disks.
            - When creating new VM, the first configured disk in the O(disk[]) list will be "Hard Disk 1".
  nvdimm:
    description:
    - Add or remove a virtual NVDIMM device to the virtual machine.
    - VM virtual hardware version must be 14 or higher on vSphere 6.7 or later.
    - Verify that guest OS of the virtual machine supports PMem before adding virtual NVDIMM device.
    - Verify that you have the I(Datastore.Allocate) space privilege on the virtual machine.
    - Make sure that the host or the cluster on which the virtual machine resides has available PMem resources.
    - To add or remove virtual NVDIMM device to the existing virtual machine, it must be in power off state.
    type: dict
    default: {}
    suboptions:
        state:
             type: str
             description:
             - If set to V(absent), then the NVDIMM device with specified O(nvdimm.label) will be removed.
             choices: ['present', 'absent']
        size_mb:
            type: int
            description: Virtual NVDIMM device size in MB.
            default: 1024
        label:
             type: str
             description:
             - The label of the virtual NVDIMM device to be removed or configured, e.g., "NVDIMM 1".
             - 'This parameter is required when O(nvdimm.state=absent), or O(nvdimm.state=present) to reconfigure NVDIMM device
               size. When add a new device, please do not set.'
  cdrom:
    description:
    - A list of CD-ROM configurations for the virtual machine.
    - For V(ide) controller, hot-add or hot-remove CD-ROM is not supported.
    type: list
    default: []
    elements: dict
    suboptions:
        type:
            type: str
            description:
            - The type of CD-ROM.
            - With V(none) the CD-ROM will be disconnected but present.
            choices: [ 'none', 'client', 'iso' ]
            default: client
        iso_path:
            type: str
            description:
            - The datastore path to the ISO file to use, in the form of C([datastore1] path/to/file.iso).
            - Required if type is set V(iso).
        controller_type:
            type: str
            description:
            - When set to V(sata), please make sure O(cdrom[].unit_number) is correct and not used by SATA disks.
            choices: [ 'ide', 'sata' ]
            default: ide
        controller_number:
            type: int
            description:
            - For O(cdrom[].controller_type=ide), valid value is 0 or 1.
            - For O(cdrom[].controller_type=sata), valid value is 0 to 3.
        unit_number:
            type: int
            description:
            - For O(cdrom[].controller_type=ide), valid value is 0 or 1.
            - For O(cdrom[].controller_type=sata), valid value is 0 to 29.
            - O(cdrom[].controller_number) and O(cdrom[].unit_number) are mandatory attributes.
        state:
            type: str
            description:
            - If set to V(absent), then the specified CD-ROM will be removed.
            choices: [ 'present', 'absent' ]
            default: present
  resource_pool:
    description:
    - Use the given resource pool for virtual machine operation.
    - Resource pool should be child of the selected host parent.
    - When not specified I(Resources) is taken as default value.
    type: str
  wait_for_ip_address:
    description:
    - Wait until vCenter detects an IP address for the virtual machine.
    - This requires vmware-tools (vmtoolsd) to properly work after creation.
    - "vmware-tools needs to be installed on the given virtual machine in order to work with this parameter."
    default: false
    type: bool
  wait_for_ip_address_timeout:
    description:
    - Define a timeout (in seconds) for the wait_for_ip_address parameter.
    default: '300'
    type: int
  wait_for_customization_timeout:
    description:
    - Define a timeout (in seconds) for the wait_for_customization parameter.
    - Be careful when setting this value since the time guest customization took may differ among guest OSes.
    default: '3600'
    type: int
  wait_for_customization:
    description:
    - Wait until vCenter detects all guest customizations as successfully completed.
    - When enabled, the VM will automatically be powered on.
    - "If vCenter does not detect guest customization start or succeed, failed events after time
      O(wait_for_customization_timeout) parameter specified, warning message will be printed and task result is fail."
    default: false
    type: bool
  state_change_timeout:
    description:
    - If the O(state=shutdownguest), by default the module will return immediately after sending the shutdown signal.
    - If this argument is set to a positive integer, the module will instead wait for the virtual machine to reach the poweredoff state.
    - The value sets a timeout in seconds for the module to wait for the state change.
    default: 0
    type: int
  snapshot_src:
    description:
    - Name of the existing snapshot to use to create a clone of a virtual machine.
    - While creating linked clone using O(linked_clone) parameter, this parameter is required.
    type: str
  linked_clone:
    description:
    - Whether to create a linked clone from the snapshot specified.
    - If specified, then O(snapshot_src) is required parameter.
    default: false
    type: bool
  force:
    description:
    - Ignore warnings and complete the actions.
    - This parameter is useful while removing virtual machine which is powered on state.
    - 'This module reflects the VMware vCenter API and UI workflow, as such, in some cases the `force` flag will
       be mandatory to perform the action to ensure you are certain the action has to be taken, no matter what the consequence.
       This is specifically the case for removing a powered on the virtual machine when O(state=absent).'
    default: false
    type: bool
  delete_from_inventory:
    description:
    - Whether to delete Virtual machine from inventory or delete from disk.
    default: false
    type: bool
  datacenter:
    description:
    - Destination datacenter for the deploy operation.
    default: ha-datacenter
    type: str
  cluster:
    description:
    - The cluster name where the virtual machine will run.
    - This is a required parameter, if O(esxi_hostname) is not set.
    - O(esxi_hostname) and O(cluster) are mutually exclusive parameters.
    type: str
  esxi_hostname:
    description:
    - The ESXi hostname where the virtual machine will run.
    - This is a required parameter, if O(cluster) is not set.
    - O(esxi_hostname) and O(cluster) are mutually exclusive parameters.
    type: str
  advanced_settings:
    description:
    - Define a list of advanced settings to be added to the VMX config.
    - An advanced settings object takes the two fields C(key) and C(value).
    - Incorrect key and values will be ignored.
    elements: dict
    type: list
    default: []
  annotation:
    description:
    - A note or annotation to include in the virtual machine.
    type: str
    aliases: [ 'notes' ]
  customvalues:
    description:
    - Define a list of custom values to set on virtual machine.
    - A custom value object takes the two fields C(key) and C(value).
    - Incorrect key and values will be ignored.
    elements: dict
    type: list
    default: []
  networks:
    description:
    - A list of networks (in the order of the NICs).
    - Removing NICs is not allowed, while reconfiguring the virtual machine.
    - The I(type), I(ip), I(netmask), I(gateway), I(domain), I(dns_servers) options don't set to a guest when creating a blank new virtual machine.
      They are set by the customization via vmware-tools.
      If you want to set the value of the options to a guest, you need to clone from a template with installed OS and vmware-tools (also Perl when Linux).
    type: list
    default: []
    elements: dict
    suboptions:
        name:
            type: str
            description:
            - Name of the portgroup or distributed virtual portgroup for this interface.
            - This is required if C(vlan) isn't defined.
            - When specifying distributed virtual portgroup make sure given O(esxi_hostname) or O(cluster) is associated with it.
        vlan:
            type: int
            description:
            - VLAN number for this interface.
            - This is required if C(name) isn't defined.
        device_type:
            type: str
            description:
            - Virtual network device.
            - Valid value can be one of C(e1000), C(e1000e), C(pcnet32), C(vmxnet2), C(vmxnet3), C(sriov).
            - C(vmxnet3) is default.
            - Optional per entry.
            - Used for virtual hardware.
        mac:
            type: str
            description:
            - Customize MAC address.
            - Optional per entry.
            - Used for virtual hardware.
        dvswitch_name:
            type: str
            description:
            - Name of the distributed vSwitch.
            - Optional per entry.
            - Used for virtual hardware.
        type:
            type: str
            description:
            - Type of IP assignment.
            - Valid values are one of C(dhcp), C(static).
            - C(dhcp) is default.
            - Optional per entry.
            - Used for OS customization.
        ip:
            type: str
            description:
            - Static IP address. Implies C(type=static).
            - Optional per entry.
            - Used for OS customization.
        netmask:
            type: str
            description:
            - Static netmask required for C(ip).
            - Optional per entry.
            - Used for OS customization.
        gateway:
            type: str
            description:
            - Static gateway.
            - Optional per entry.
            - Used for OS customization.
        typev6:
            version_added: '4.1.0'
            type: str
            description:
            - Type of IP assignment.
            - Valid values are one of C(dhcp), C(static).
            - C(dhcp) is default.
            - Optional per entry.
            - Used for OS customization.
        ipv6:
            version_added: '4.1.0'
            type: str
            description:
            - Static IP address. Implies C(type=static).
            - Optional per entry.
            - Used for OS customization.
        netmaskv6:
            version_added: '4.1.0'
            type: str
            description:
            - Static netmask required for C(ip).
            - Optional per entry.
            - Used for OS customization.
        gatewayv6:
            version_added: '4.1.0'
            type: str
            description:
            - Static gateway.
            - Optional per entry.
            - Used for OS customization.
        dns_servers:
            type: str
            description:
            - DNS servers for this network interface (Windows).
            - Optional per entry.
            - Used for OS customization.
        domain:
            type: str
            description:
            - Domain name for this network interface (Windows).
            - Optional per entry.
            - Used for OS customization.
        connected:
            type: bool
            description:
            - Indicates whether the NIC is currently connected.
        start_connected:
            type: bool
            description:
            - Specifies whether or not to connect the device when the virtual machine starts.
  customization:
    description:
    - Parameters for OS customization when cloning from the template or the virtual machine, or apply to the existing virtual machine directly.
    - Not all operating systems are supported for customization with respective vCenter version,
      please check VMware documentation for respective OS customization.
    - For supported customization operating system matrix, (see U(http://partnerweb.vmware.com/programs/guestOS/guest-os-customization-matrix.pdf))
    - Linux based OSes requires Perl package to be installed for OS customizations.
    suboptions:
        existing_vm:
            type: bool
            description:
            - If set to V(true), do OS customization on the specified virtual machine directly.
            - Common for Linux and Windows customization.
        dns_servers:
            type: list
            elements: str
            description:
            - List of DNS servers to configure.
            - Common for Linux and Windows customization.
        dns_suffix:
            type: list
            elements: str
            description:
            - List of domain suffixes, also known as DNS search path.
            - Default C(domain) parameter.
            - Common for Linux and Windows customization.
        domain:
            type: str
            description:
            - DNS domain name to use.
            - Common for Linux and Windows customization.
        hostname:
            type: str
            description:
            - Computer hostname.
            - Default is shortened O(name) parameter.
            - Allowed characters are alphanumeric (uppercase and lowercase) and minus, rest of the characters are dropped as per RFC 952.
            - Common for Linux and Windows customization.
        timezone:
            type: str
            description:
            - Timezone.
            - See List of supported time zones for different vSphere versions in Linux/Unix.
            - Common for Linux and Windows customization.
            - L(Windows, https://msdn.microsoft.com/en-us/library/ms912391.aspx).
        hwclockUTC:
            type: bool
            description:
            - Specifies whether the hardware clock is in UTC or local time.
            - Specific to Linux customization.
        script_text:
            type: str
            description:
            - Script to run with shebang.
            - Needs to be enabled in vmware tools with vmware-toolbox-cmd config set deployPkg enable-custom-scripts true
            - https://docs.vmware.com/en/VMware-vSphere/7.0/com.vmware.vsphere.vm_admin.doc/GUID-9A5093A5-C54F-4502-941B-3F9C0F573A39.html
            - Specific to Linux customization.
            version_added: '3.1.0'
        autologon:
            type: bool
            description:
            - Auto logon after virtual machine customization.
            - Specific to Windows customization.
        autologoncount:
            type: int
            description:
            - Number of autologon after reboot.
            - Specific to Windows customization.
            - Ignored if O(customization.autologon) is unset or set to O(customization.autologon=false).
            - If unset, 1 will be used.
        domainadmin:
            type: str
            description:
            - User used to join in AD domain.
            - Required if O(customization.joindomain) specified.
            - Specific to Windows customization.
        domainadminpassword:
            type: str
            description:
            - Password used to join in AD domain.
            - Required if O(customization.joindomain) specified.
            - Specific to Windows customization.
        fullname:
            type: str
            description:
            - Server owner name.
            - Specific to Windows customization.
            - If unset, "Administrator" will be used as a fall-back.
        joindomain:
            type: str
            description:
            - AD domain to join.
            - Not compatible with O(customization.joinworkgroup).
            - Specific to Windows customization.
        joinworkgroup:
            type: str
            description:
            - Workgroup to join.
            - Not compatible with O(customization.joindomain).
            - Specific to Windows customization.
            - If unset, "WORKGROUP" will be used as a fall-back.
        orgname:
            type: str
            description:
            - Organization name.
            - Specific to Windows customization.
            - If unset, "ACME" will be used as a fall-back.
        password:
            type: str
            description:
            - Local administrator password.
            - If not defined, the password will be set to blank (that is, no password).
            - Specific to Windows customization.
        productid:
            type: str
            description:
            - Product ID.
            - Specific to Windows customization.
        runonce:
            type: list
            elements: str
            description:
            - List of commands to run at first user logon.
            - Specific to Windows customization.
        domain_ou:
            type: str
            description:
            - The full LDAP path name of the OU to which the computer belongs.
            - Specific to Windows customization.
            - Work for vSphere 8.0U2 and above
    type: dict
    default: {}
  vapp_properties:
    description:
    - A list of vApp properties.
    - 'For full list of attributes and types refer to: U(https://code.vmware.com/apis/704/vsphere/vim.vApp.PropertyInfo.html)'
    type: list
    default: []
    elements: dict
    suboptions:
        id:
            type: str
            description:
            - Property ID.
            - Required per entry.
        value:
            type: str
            description:
            - Property value.
        type:
            type: str
            description:
            - Value type, string type by default.
        operation:
            type: str
            description:
            - The C(remove) attribute is required only when removing properties.
  customization_spec:
    description:
    - Unique name identifying the requested customization specification.
    - If set, then overrides O(customization) parameter values.
    type: str
  datastore:
    description:
    - Specify datastore or datastore cluster to provision virtual machine.
    - This parameter takes precedence over O(disk[].datastore) parameter.
    - This parameter can be used to override datastore or datastore cluster setting
      of the virtual machine when deployed from the template.
    - Please see example for more usage.
    type: str
  convert:
    description:
    - Specify convert disk type while cloning template or virtual machine.
    choices: [ 'thin', 'thick', 'eagerzeroedthick' ]
    type: str
extends_documentation_fragment:
- community.vmware.vmware.documentation

ab  
- name: Create a virtual machine on given ESXi hostname
  community.vmware.vmware_guest:
    hostname: "{{ vcenter_hostname }}"
    username: "{{ vcenter_username }}"
    password: "{{ vcenter_password }}"
    folder: /DC1/vm/
    name: test_vm_0001
    state: poweredon
    guest_id: centos64Guest
    # This is hostname of particular ESXi server on which user wants VM to be deployed
    esxi_hostname: "{{ esxi_hostname }}"
    disk:
    - size_gb: 10
      type: thin
      datastore: datastore1
    hardware:
      memory_mb: 512
      num_cpus: 4
      scsi: paravirtual
    networks:
    - name: VM Network
      mac: aa:bb:dd:aa:00:14
      ip: 10.10.10.100
      netmask: 255.255.255.0
      device_type: vmxnet3
    wait_for_ip_address: true
    wait_for_ip_address_timeout: 600
  delegate_to: localhost
  register: deploy_vm

- name: Create a virtual machine from a template
  community.vmware.vmware_guest:
    hostname: "{{ vcenter_hostname }}"
    username: "{{ vcenter_username }}"
    password: "{{ vcenter_password }}"
    folder: /testvms
    name: testvm_2
    state: poweredon
    template: template_el7
    disk:
    - size_gb: 10
      type: thin
      datastore: g73_datastore
    # Add another disk from an existing VMDK
    - filename: "[datastore1] testvms/testvm_2_1/testvm_2_1.vmdk"
    hardware:
      memory_mb: 512
      num_cpus: 6
      num_cpu_cores_per_socket: 3
      scsi: paravirtual
      memory_reservation_lock: true
      mem_limit: 8096
      mem_reservation: 4096
      cpu_shares_level: "high"
      mem_shares_level: "high"
      cpu_limit: 8096
      cpu_reservation: 4096
      max_connections: 5
      hotadd_cpu: true
      hotremove_cpu: true
      hotadd_memory: false
      version: 12 # Hardware version of virtual machine
      boot_firmware: "efi"
    cdrom:
        - controller_number: 0
          unit_number: 0
          state: present
          type: iso
          iso_path: "[datastore1] livecd.iso"
    networks:
    - name: VM Network
      mac: aa:bb:dd:aa:00:14
    wait_for_ip_address: true
  delegate_to: localhost
  register: deploy

- name: Clone a virtual machine from Windows template and customize
  community.vmware.vmware_guest:
    hostname: "{{ vcenter_hostname }}"
    username: "{{ vcenter_username }}"
    password: "{{ vcenter_password }}"
    datacenter: datacenter1
    cluster: cluster
    name: testvm-2
    template: template_windows
    networks:
    - name: VM Network
      ip: 192.168.1.100
      netmask: 255.255.255.0
      gateway: 192.168.1.1
      mac: aa:bb:dd:aa:00:14
      domain: my_domain
      dns_servers:
      - 192.168.1.1
      - 192.168.1.2
    - vlan: 1234
      type: dhcp
    customization:
      autologon: true
      dns_servers:
      - 192.168.1.1
      - 192.168.1.2
      domain: my_domain
      password: new_vm_password
      runonce:
      - powershell.exe -ExecutionPolicy Unrestricted -File C:\Windows\Temp\ConfigureRemotingForAnsible.ps1 -ForceNewSSLCert -EnableCredSSP
  delegate_to: localhost

- name:  Clone a virtual machine from Linux template and customize
  community.vmware.vmware_guest:
    hostname: "{{ vcenter_hostname }}"
    username: "{{ vcenter_username }}"
    password: "{{ vcenter_password }}"
    datacenter: "{{ datacenter }}"
    state: present
    folder: /DC1/vm
    template: "{{ template }}"
    name: "{{ vm_name }}"
    cluster: DC1_C1
    networks:
      - name: VM Network
        ip: 192.168.10.11
        netmask: 255.255.255.0
    wait_for_ip_address: true
    customization:
      domain: "{{ guest_domain }}"
      dns_servers:
        - 8.9.9.9
        - 7.8.8.9
      dns_suffix:
        - example.com
        - example2.com
      script_text: |
        #!/bin/bash
        touch /tmp/touch-from-playbook
  delegate_to: localhost

- name: Rename a virtual machine (requires the virtual machine's uuid)
  community.vmware.vmware_guest:
    hostname: "{{ vcenter_hostname }}"
    username: "{{ vcenter_username }}"
    password: "{{ vcenter_password }}"
    uuid: "{{ vm_uuid }}"
    name: new_name
    state: present
  delegate_to: localhost

- name: Remove a virtual machine by uuid
  community.vmware.vmware_guest:
    hostname: "{{ vcenter_hostname }}"
    username: "{{ vcenter_username }}"
    password: "{{ vcenter_password }}"
    uuid: "{{ vm_uuid }}"
    state: absent
  delegate_to: localhost

- name: Remove a virtual machine from inventory
  community.vmware.vmware_guest:
    hostname: "{{ vcenter_hostname }}"
    username: "{{ vcenter_username }}"
    password: "{{ vcenter_password }}"
    name: vm_name
    delete_from_inventory: true
    state: absent
  delegate_to: localhost

- name: Manipulate vApp properties
  community.vmware.vmware_guest:
    hostname: "{{ vcenter_hostname }}"
    username: "{{ vcenter_username }}"
    password: "{{ vcenter_password }}"
    name: vm_name
    state: present
    vapp_properties:
      - id: remoteIP
        category: Backup
        label: Backup server IP
        type: string
        value: 10.10.10.1
      - id: old_property
        operation: remove
  delegate_to: localhost

- name: Set powerstate of a virtual machine to poweroff by using UUID
  community.vmware.vmware_guest:
    hostname: "{{ vcenter_hostname }}"
    username: "{{ vcenter_username }}"
    password: "{{ vcenter_password }}"
    uuid: "{{ vm_uuid }}"
    state: poweredoff
  delegate_to: localhost

- name: Deploy a virtual machine in a datastore different from the datastore of the template
  community.vmware.vmware_guest:
    hostname: "{{ vcenter_hostname }}"
    username: "{{ vcenter_username }}"
    password: "{{ vcenter_password }}"
    name: "{{ vm_name }}"
    state: present
    template: "{{ template_name }}"
    # Here datastore can be different which holds template
    datastore: "{{ virtual_machine_datastore }}"
    hardware:
      memory_mb: 512
      num_cpus: 2
      scsi: paravirtual
  delegate_to: localhost

- name: Create a diskless VM
  community.vmware.vmware_guest:
    hostname: "{{ vcenter_hostname }}"
    username: "{{ vcenter_username }}"
    password: "{{ vcenter_password }}"
    datacenter: "{{ dc1 }}"
    state: poweredoff
    cluster: "{{ ccr1 }}"
    name: diskless_vm
    folder: /Asia-Datacenter1/vm
    guest_id: centos64Guest
    datastore: "{{ ds1 }}"
    hardware:
        memory_mb: 1024
        num_cpus: 2
        num_cpu_cores_per_socket: 1

- name: Create a VM with multiple disks of different disk controller types
  community.vmware.vmware_guest:
    hostname: "{{ vcenter_hostname }}"
    username: "{{ vcenter_username }}"
    password: "{{ vcenter_password }}"
    folder: /DC1/vm/
    name: test_vm_multi_disks
    state: poweredoff
    guest_id: centos64Guest
    datastore: datastore1
    disk:
    - size_gb: 10
      controller_type: 'nvme'
      controller_number: 0
      unit_number: 0
    - size_gb: 10
      controller_type: 'paravirtual'
      controller_number: 0
      unit_number: 1
    - size_gb: 10
      controller_type: 'sata'
      controller_number: 0
      unit_number: 2
    hardware:
      memory_mb: 512
      num_cpus: 4
      version: 14
    networks:
    - name: VM Network
      device_type: vmxnet3
  delegate_to: localhost
  register: deploy_vm

- name: Create a VM with NVDIMM device
  community.vmware.vmware_guest:
    hostname: "{{ vcenter_hostname }}"
    username: "{{ vcenter_username }}"
    password: "{{ vcenter_password }}"
    folder: /DC1/vm/
    name: test_vm_nvdimm
    state: poweredoff
    guest_id: centos7_64Guest
    datastore: datastore1
    hardware:
      memory_mb: 512
      num_cpus: 4
      version: 14
    networks:
    - name: VM Network
      device_type: vmxnet3
    nvdimm:
      state: present
      size_mb: 2048
  delegate_to: localhost
  register: deploy_vm
zx
instance:
    description: metadata about the new virtual machine
    returned: always
    type: dict
    sample: None
N)vimvmodl)AnsibleModule)is_mac)to_text	to_native)find_objgather_vm_factsget_all_objscompile_folder_path_for_objectserialize_specset_vm_power_statePyVmomifind_dvs_by_namefind_dvspg_by_namewait_for_vm_ipquote_obj_name)base_argument_spec)PyVmomiDeviceHelper)SPBMc                   @    e Zd ZdZd
dZddZddZd Zd Zd Z	d	 Z
y)PyVmomiCachez^ This class caches references to objects which are requested multiples times but not modified Nc                 X    || _         || _        i | _        i | _        i | _        i | _        y N)contentdc_namenetworksclusters	esx_hostsparent_datacenters)selfr   r   s      q/home/dcms/DCMS/lib/python3.12/site-packages/ansible_collections/community/vmware/plugins/modules/vmware_guest.py__init__zPyVmomiCache.__init__p  s-    "$    c                 $   t        |||      }|r|r~t        | j                  |      j                        t        | j                        k7  rDd}| j                  ||d      }|D ])  }|"t        |j                        t        |      k(  s'|c S  |S )z3 Wrapper around find_obj to set datacenter context NT)confine_to_datacenter)r   r
   get_parent_datacenternamer   r   )r$   r   typesr+   r)   resultobjectsobjs           r%   r   zPyVmomiCache.find_objx  s    '5$/+t11&9>>?74<<CXX++GURV+W" #C|wsxx'8GDM'I"
# r'   c                 V   t        ||      }|rt        |d      rQt        |j                               D ]3  \  }}| j	                  |      }|j
                  | j                  k7  s1||= 5 |S |D cg c]-  }| j	                  |      j
                  | j                  k(  s,|/ }}|S c c}w )z7 Wrapper around get_all_objs to set datacenter context items)r   hasattrtupler1   r*   r+   r   )	r$   r   r,   r)   r.   kv	parent_dcxs	            r%   r   zPyVmomiCache.get_all_objs  s    w. w( "'--/2 'DAq $ : :1 =I ~~5#AJ'  '.d1K1KA1N1S1SW[WcWc1c1dd es   0-B&B&c                 (   t        |      }|| j                  vrk| j                  |      }t        |      dk(  r|d   | j                  |<   n9| j	                  | j
                  t        j                  g|      | j                  |<   | j                  |   S )N   r   )r   r    find_network_by_namelenr   r   r   Network)r$   network_namer    s      r%   get_networkzPyVmomiCache.get_network  s{    %l3t}},00>H8}!.6qkl+.2mmDLL3;;-Ye.fl+}}\**r'   c                     || j                   vr9| j                  | j                  t        j                  g|      | j                   |<   | j                   |   S r   )r!   r   r   r   ClusterComputeResource)r$   clusters     r%   get_clusterzPyVmomiCache.get_cluster  sF    $--'%)]]4<<#B\B\A]_f%gDMM'"}}W%%r'   c                     || j                   vr9| j                  | j                  t        j                  g|      | j                   |<   | j                   |   S r   )r"   r   r   r   
HostSystem)r$   hosts     r%   get_esx_hostzPyVmomiCache.get_esx_host  sD    t~~%#'==?OQU#VDNN4 ~~d##r'   c                 
   t        |t        j                        r|S || j                  v r| j                  |   S d}	 t	        |d      sn*|j
                  }t        |t        j                        r|}n7|| j                  |<   |S )z5 Walk the parent tree to find the objects datacenter Nparent)
isinstancer   
Datacenterr#   r2   rH   )r$   r/   
datacenters      r%   r*   z"PyVmomiCache.get_parent_datacenter  s    c3>>*J$)))**3//
3)**C#s~~. 
  (2$r'   r   )T)__name__
__module____qualname____doc__r&   r   r   r>   rB   rF   r*    r'   r%   r   r   m  s(    h%
"
+&$r'   r   c                   P    e Zd Z fdZd Zd0dZd0dZd Zd0dZd Z	d Z
d	 Zd
 Zd Zd1dZd2dZd2dZd2dZd2dZd2dZd Zd2dZd Zd Zd Zd Zd Zd Zd Zd Zd Zd Zd Z d0dZ!d  Z"d! Z#d" Z$d# Z%d2d$Z&d% Z'd& Z(d' Z)d3d(Z*d) Z+d* Z,d+ Z-d, Z.d4d-Z/d. Z0d5d/Z1 xZ2S )6PyVmomiHelperc                    t         t        |   |       t        | j                        | _        d | _        d | _        d| _        d| _	        i | _
        d | _        t        | j                  | j                  d         | _        y )NFrK   )r   )superrR   r&   r   moduledevice_helper
configspecrelospecchange_detectedchange_appliedtracked_changes
customspecr   r   paramscache)r$   rU   	__class__s     r%   r&   zPyVmomiHelper.__init__  sk    mT+F30=$#!!$,,L8QR
r'   c                 .    t        | j                  |      S r   )r   r   r$   vms     r%   gather_factszPyVmomiHelper.gather_facts  s    t||R00r'   c                 f   |j                   j                  j                  j                         dk(  r)| j                  j                  d|j                  z         |r'	 |j                          d| _        | j                  ddS |j                         }| j!                  |      }|j"                  j$                  d	k(  r| j                  d|d
dS | j                  ddS # t        j                  j                  t        j                  f$ r%}| j                  d|j                  ddcY d }~S d }~ww xY w)N	poweredonzVirtual machine %s found in 'powered on' state, please use 'force' parameter to remove or poweroff VM and try removing VM again.msgTUnregisterVMchangedfailedrg   opFrj   rk   errordestroy)summaryruntime
powerStatelowerrU   	fail_jsonr+   rh   r   faultTaskInProgressr   RuntimeFaultrZ   rg   Destroywait_for_taskinfostate)r$   rb   delete_from_inventoryetask	error_msgs         r%   	remove_vmzPyVmomiHelper.remove_vm  s   ::((..0K?KK!! 'CEGWW'M! N !l! #'D#22eDDzz|&&t,	99??g%#22d9\eff#22eDD II,,&&( l#'#6#6$quu\jkkls   C -D0D+%D0+D0c                    | j                   d   ry |r+| j                   d   | j                  j                  d       | j                   d   ru|L| j                   d   j                         |j                  j
                  j                  j                         k7  r&d| _        | j                   d   | j                  _        y y y )Ntemplateguest_idz/guest_id attribute is mandatory for VM creationrf   T)	r]   rU   rt   rs   rp   configguestIdrY   rW   )r$   vm_objvm_creations      r%   configure_guestidzPyVmomiHelper.configure_guestid  s    ;;z" 4;;z2:KK!!&W!X;;z"4;;z#:#@#@#BfnnF[F[FcFcFiFiFk#k#'D &*kk*&=DOO# $l #r'   c                 d   d}t        j                         }t        j                         }t        j                         }t        j                         }| j                  d   d   }|S||_        ||_        |A|j
                  j                  |j                  j                  j
                  j                  k7  rd}| j                  d   d   }|S||_        ||_        |A|j
                  j                  |j                  j                  j
                  j                  k7  rd}| j                  d   d   }	|	Fd|_        |	|_        ||_        |-|j
                  |j                  j                  j
                  k7  rd}| j                  d   d	   }
|
Fd|_        |
|_        ||_        |-|j
                  |j                  j                  j
                  k7  rd}| j                  d   d
   }|8||_	        |-|j                  |j                  j                  j                  k7  rd}| j                  d   d   }|8||_
        |-|j                  |j                  j                  j                  k7  rd}| j                  d   d   }|8||_	        |-|j                  |j                  j                  j                  k7  rd}| j                  d   d   }|8||_
        |-|j                  |j                  j                  j                  k7  rd}|r*|| j                  _        || j                  _        d| _        yy)z
        Function to configure resource allocation information about virtual machine
        :param vm_obj: VM object in case of reconfigure, None in case of deploy
        :return: None
        Fhardwaremem_shares_levelNTcpu_shares_level
mem_sharescustom
cpu_shares	mem_limitmem_reservation	cpu_limitcpu_reservation)r   ResourceAllocationInfo
SharesInfor]   levelsharesr   memoryAllocationcpuAllocationlimitreservationrW   rY   )r$   r   rai_change_detectedmemory_allocationcpu_allocationmemory_shares_infocpu_shares_infor   r   r   r   r   r   r   r   s                  r%   configure_resource_alloc_infoz+PyVmomiHelper.configure_resource_alloc_info  s    $668335 ^^-..*;;z23EF''7$'9$~%,,22fmm6T6T6[6[6a6aa&*#;;z23EF'$4O!$3N!~"))//6==3N3N3U3U3[3[[&*#[[,\:
!'/$(2%'9$~%,,0N0N0U0UU&*#[[,\:
!$,O!%/O"$3N!~"))V]]-H-H-O-OO&*#KK
+K8	 &/#~%++v}}/M/M/S/SS&*#++j12CD&,;)~%11V]]5S5S5_5__&*#KK
+K8	 #,N ~"((FMM,G,G,M,MM&*#++j12CD&)8N&~"..&--2M2M2Y2YY&*#/@DOO,,:DOO)#'D  r'   c                    | j                   d   d   }||r|j                  j                  t        j                  j
                  k(  r| j                  j                  s|j                  j                  s?||j                  j                  j                  k  r| j                  j                  d       |j                  j                  s?||j                  j                  j                  kD  r| j                  j                  d       | j                   d   d   }|a||z  dk7  r| j                  j                  d       |#||j                  j                  j                  k7  rd	| _        || j                   _        |#||j                  j                  j                  k7  rFd	| _        || j                   _        n-|r+| j                   d
   s| j                  j                  d       | j                   d   d   }|2|r|j                  j                  t        j                  j
                  k(  r|j                  j$                  r@||j                  j                  j&                  k  r| j                  j                  d       nk|j                  j$                  sU||j                  j                  j&                  k7  r2| j                  j                  s| j                  j                  d       |#||j                  j                  j&                  k7  rFd	| _        || j                   _        n-|r+| j                   d
   s| j                  j                  d       | j                   d   d   }||r||j                  j                  t        j                  j
                  k(  rK|j                  j$                  |k7  r2| j                  j                  s| j                  j                  d       |||j                  j$                  k7  rd	| _        || j                   _        | j                   d   d   }||r||j                  j                  t        j                  j
                  k(  rK|j                  j                  |k7  r2| j                  j                  s| j                  j                  d       |||j                  j                  k7  rd	| _        || j                   _        | j                   d   d   }||r||j                  j                  t        j                  j
                  k(  rK|j                  j                  |k7  r2| j                  j                  s| j                  j                  d       |||j                  j                  k7  rd	| _        || j                   _	        | j                   d   d   }	|	3||	|j                  j(                  k7  rd	| _        |	| j                   _        | j                   d   d   }
|
|r||j                  j                  t        j                  j
                  k(  rK|j                  j*                  |
k7  r2| j                  j                  s| j                  j                  d       ||
|j                  j*                  k7  rd	| _        |
| j                   _        | j                   d   d   }||y || j                   _        d	| _        y y )Nr   num_cpuszXConfigured cpu number is less than the cpu number of the VM, cpuHotRemove is not enabledrf   zUConfigured cpu number is more than the cpu number of the VM, cpuHotAdd is not enablednum_cpu_cores_per_socketr   zUhardware.num_cpus attribute should be a multiple of hardware.num_cpu_cores_per_socketTr   z8hardware.num_cpus attribute is mandatory for VM creation	memory_mbzPConfigured memory is less than memory size of the VM, operation is not supportedzmemoryHotAdd is not enabledz9hardware.memory_mb attribute is mandatory for VM creationhotadd_memoryzFConfigure hotadd memory operation is not supported when VM is power on
hotadd_cpuzCConfigure hotadd cpu operation is not supported when VM is power onhotremove_cpuzFConfigure hotremove cpu operation is not supported when VM is power onmemory_reservation_lockvpmc_enabledzAConfigure vPMC cpu operation is not supported when VM is power onboot_firmware)r]   rq   rr   r   VirtualMachinePowerState	poweredOnrU   
check_moder   cpuHotRemoveEnabledr   numCPUrt   cpuHotAddEnablednumCoresPerSocketrY   rW   numCPUsmemoryHotAddEnabledmemoryMBmemoryReservationLockedToMaxvPMCEnabledfirmware)r$   r   r   r   r   r   r   r   r   r   r   r   s               r%   configure_cpu_and_memoryz&PyVmomiHelper.configure_cpu_and_memoryD  s   ;;z*:6 &..33s7S7S7]7]]fjfqfqf|f|}}88XH^H^HeHe=eKK)) /L) M}}55(V]]E[E[EbEb:bKK)) /I) J (,{{:'>?Y'Z$'366!;KK)) /U) V>%=AWAWAiAi%i+/D(8PDOO5~V]]-C-C-J-J!J'+$*2'Z!8KK!!&`!aKK
+K8	 &..33s7S7S7]7]]==44V]]E[E[EdEd9dKK)) /K) L  ::yFMMLbLbLkLk?ktxtt  uK  uKKK)).K)L~fmm.D.D.M.M!M'+$+4(Z!8KK!!&a!bJ/@$&..33s7S7S7]7]]MM55Ft{{OeOe%%*r%s~&--2S2S!S'+$6C3[[,\:
!&..33s7S7S7]7]]MM22j@I_I_%%*o%p~v}}/M/M!M'+$3=0J/@$&..33s7S7S7]7]]MM55Ft{{OeOe%%*r%s~&--2S2S!S'+$6C3"&++j"9:S"T".~!8FMM<f<f!f'+$?V<{{:.~>#&..33s7S7S7]7]]MM--=dkkF\F\%%*m%n~1J1J!J'+$.:+J/@$!'4DOO$#'D  %r'   c                    g }| j                   j                  d      }|rO|D ]I  }|j                  d      |d<   |j                  d      |d<   |d   dk(  rI|j                  d      |d<   |d   dk(  r-|j                  d      s| j                  j                  d	       d
|vsd|vr| j                  j                  d	       t	        |j                  d
            }t	        |j                  d            }|d   dk(  rI|dvs|dvrA| j                  j                  d|j                  d
      d|j                  d      d	       |d   dk(  r]|t        dd      vs|t        dd      vrA| j                  j                  d|j                  d
      d|j                  d      d	       ||d
<   ||d<   d}|D ]  }|j                  d      |d
   k(  s|j                  d      |d   k(  s3|d   D ]=  }|d   |d   k(  s| j                  j                  d|d   d|d
   d|d   d	       ? d}|d   j                  |        n |r.|j                  |d
   |d   |gd        L |S )!Ncdromcontroller_typer{   presenttypeisoiso_pathz:cdrom.iso_path is mandatory when cdrom.type is set to iso.rf   controller_numberunit_numberzd'cdrom.controller_number' and 'cdrom.unit_number' are required parameters when configure CDROM list.ide)r   r9   z!Invalid cdrom.controller_number: z or cdrom.unit_number: z-, valid values are 0 or 1 for IDE controller.satar         zV, valid controller_number value is 0-3, valid unit_number is 0-29 for SATA controller.Fctl_numctl_typecdromsz!Duplicate cdrom.controller_type: z, cdrom.controller_number: z,cdrom.unit_number: z parameters specified.T)r   r   r   )r]   getrU   rt   intrangeappend)	r$   cdrom_specsexpected_cdrom_spec
cdrom_speccdrom_ctl_numcdrom_ctl_unit_num	ctl_exist
exist_speccdrom_same_ctls	            r%   sanitize_cdrom_paramsz#PyVmomiHelper.sanitize_cdrom_params  s   "kkoog61 ,l
0:?P0Q
,-&0nnW&=
7#g&)3)3)?Jv&!&)U2:>>*;U--2n-o&j8MQ[<[KK)) /W) X !$JNN3F$G H%()F%G"/0E9}TZ?Z^px~^~KK))1;@S1TV`VdVderVs/u) v /0F:UZ[\^_U`@`dv  D  EF  HJ  K  eKKK))ISXkIlISXeIf/h) i 3@
./,>
=)!	"- 
J!~~i0J?R4SS&NN:6*EV:WW.8.B YN-m<
=@YY $ 5 5=GHY=Z\fgz\{  ~H  IV  ~W;X 5 !YY
 %)	"8,33J?
 !&&:>Q3R4>?P4Q^h]i(k lW,l\ r'   c                     | j                   j                  d      r+|r|j                  j                  ry | j	                  |       y y )Nr   )r]   r   r   r   configure_cdrom_list)r$   r   s     r%   configure_cdromzPyVmomiHelper.configure_cdrom  s7    ;;??7#&--00%%f- $r'   c                 
   | j                         }| j                  |      }| j                  |      }| j                  |      }|D ]  }d }|d   dk(  r|r|D ]  }|j                  |d   k(  s|} n |d   dk(  r|r|D ]  }|j                  |d   k(  s|} n |s|d   dk(  rW| j
                  j                  |d         }	|	j                  }d| _        | j                  j                  j                  |	       |d   dk(  rW| j
                  j                  |d         }
|
j                  }d| _        | j                  j                  j                  |
       |d   D ]  }d }|j                  d	      }|j                  d
      }|D ]/  }|j                  |j                  k(  s|j                   |k(  s-|} n |s|j                  d      dk7  r|r|j"                  j$                  t&        j(                  j*                  k(  r`t-        |t&        j.                  j                  j0                        r2| j2                  j4                  s| j2                  j7                  d       t9        |j                        dk(  rJt-        |t&        j.                  j                  j0                        r| j2                  j7                  d       t9        |j                        dk(  rJt-        |t&        j.                  j                  j:                        r| j2                  j7                  d       | j
                  j=                  ||d   ||      }d| _        | j                  j                  j                  |       |r|j                  d      dk7  r| j
                  j?                  |||d   |      s| j
                  jA                  ||||       t&        j.                  j                  jC                         }t&        j.                  j                  jB                  jD                  jF                  |_$        ||_        d| _        | j                  j                  j                  |       |s|j                  d      dk(  s&|r|j"                  j$                  t&        j(                  jJ                  k7  r`t-        |t&        j.                  j                  j0                        r2| j2                  j4                  s| j2                  j7                  d       | j
                  jM                  |      }d| _        | j                  j                  j                  |         y )Nrb   r   r   r   r   )
bus_numberTr   r   r   r{   absentz4CD-ROM attach to IDE controller not support hot-add.rf      z:Maximum number of CD-ROMs attached to IDE controller is 2.r   z<Maximum number of CD-ROMs attached to SATA controller is 30.r   )
ctl_device
cdrom_typer   r   )r   cdrom_devicer   r   )r   z7CD-ROM attach to IDE controller not support hot-remove.)'r   get_vm_cdrom_devicesget_vm_ide_devicesget_vm_sata_devices	busNumberrV   create_ide_controllerdevicerY   rW   deviceChanger   create_sata_controllerr   controllerKeykey
unitNumberrq   rr   r   r   r   rI   rb   VirtualIDEControllerrU   r   rt   r;   VirtualAHCIControllercreate_cdromis_equal_cdromupdate_cdrom_configVirtualDeviceSpec	Operationedit	operation
poweredOffremove_cdrom)r$   r   configured_cdromscdrom_deviceside_devicessata_devicesr   r   r   ide_ctlsata_ctlr   r   r   r   target_cdromr   s                    r%   r   z"PyVmomiHelper.configure_cdrom_list  s    66811V1<---8//6/:#4 B	DJ":.%7K) F''+>y+II%+
 #:.&8\* F''+>y+II%+

 &z2e;"00FFRefoRpFqG!(J+/D(OO0077@&z2f<#11HHTghqTrHsH!)J+/D(OO0077A,X6 )D# 99Z0#ii6$1 L#11Z^^CH_H_cnHn'3
 $		'(:h(F&..";";s?[?[?e?e"e&z366==3U3UV_c_j_j_u_u--2h-i:,,-2z*cffmmNpNp7q--2n-o:,,-3
:svv}}OrOr8s--2p-q!%!3!3!@!@JchiocpJR`k "A "mJ+/D(OO0077
C!eii&8H&D ..==VZfINvai > k&&::65,ai:j!$!@!@!BJ+.66==+J+J+T+T+Y+YJ((4J%+/D(OO0077
C!eii&8H&D&..";";s?[?[?f?f"f&z366==3U3UV_c_j_j_u_u--2k-l!%!3!3!@!@!NJ+/D(OO0077
CS)D3B	Dr'   c                    | j                   d   d   }|3|||j                  j                  k7  rd| _        || j                  _        | j                   d   d   }|<|"|t        |j                  j                        k7  rd| _        || j                  _        | j                   d   d   }|d}|j                         dk(  r|r|j                  j                  ss|j                  j                         }|D cg c]6  }|j                  st        |j                  j                  d      d	         8 }}t        |      }n	 t        |      }t'        |t              rd|z  }|d| _        || j                  _        n|j                  j                  s|j                  j(                  }	t        |	j                  dd	      d         }
||
k  r"| j"                  j%                  d|
|fz         n||
kD  rd| _        || j*                  d<   || j                  _        | j"                  j,                  sS|j/                  |      }| j1                  |      }|j2                  j4                  dk(  r| j6                  d|ddS d| _        | j                   d   d   }|t|#||j                  j8                  j:                  k7  rOd| _        t<        j>                  jA                         | j                  _        || j                  j8                  _        | j                   d   d   }||#||j                  jB                  jD                  k7  red| _        | j                  jB                  -t<        j>                  jG                         | j                  _!        || j                  jB                  _"        | j                   d   d   }||#||j                  jB                  jH                  k7  rfd| _        | j                  jB                  -t<        j>                  jG                         | j                  _!        || j                  jB                  _$        yyyc c}w # t         $ r# | j"                  j%                  d
|z         Y .w xY w)z
        Function to configure hardware related configuration of virtual machine
        Args:
            vm_obj: virtual machine object
        r   max_connectionsNTnested_virtversionlatest-r9   zFailed to set hardware.version '%s' value as valid values are either 'latest' or a number. Please check VMware documentation for valid VM hardware versions.rf   zvmx-%02dzCurrent hardware version '%d' which is greater than the specified version '%d'. Downgrading hardware version is not supported. Please specify version greater than the current version.zhardware.versionrn   upgraderi   secure_bootiommuvirt_based_security)%r]   r   maxMksConnectionsrY   rW   boolnestedHVEnabledrs   r   environmentBrowserQueryConfigOptionDescriptorupgradeSupportedr   r   splitmax
ValueErrorrU   rt   rI   r  r[   r   UpgradeVM_Taskry   rz   r{   rZ   bootOptionsefiSecureBootEnabledr   rb   BootOptionsflagsvvtdEnabledFlagInfo
vbsEnabled)r$   r   r   r  temp_versionnew_versionconfig_option_descriptorsoption_descavailable_hw_versionscurrent_versionversion_digitr~   r   r  r  r	  s                   r%   configure_hardware_paramsz'PyVmomiHelper.configure_hardware_params1  s    ++j12CD&~FMM4S4S!S'+$4C1kk*-m<"~V]]5R5R0S!S'+$2=/{{:.y9#K!!#x/&--"8"8060I0I0e0e0g-c|  -^T_  AL  A]  A]S1F1Fs1KA1N-O  -^)  -^#&'<#=L#&|#4L ,,(<7~'+$*5']]++"(--"7"7 #O$9$9#q$A"$E F-/KK)) /G KXJVJX/X) Y
 "M1+/D(?KD(();<.9DOO+;;11%44[A$($6$6t$<	99??g5/3/B/Bd[dlu#vv.2+kk*-m<"~0I0I0^0^!^'+$.1ff.@.@.B+CN++@J'0~&--*=*=*I*I!I'+$??((0,/FFOO,=DOO)49%%1"kk*56KL*~!48K8K8V8V!V'+$??((0,/FFOO,=DOO)3F%%0	 "W +s -^
 " KK)) /oq}/~) s   8Q
)QQ (Q<;Q<c                 R   | j                   d   d   }|3|||j                  j                  k7  rd| _        || j                  _        | j                   d   d   }|L|dk(  rd}n|dk(  rd}n|d	k(  rd
}||j                  j
                  k7  rd| _        | j                  _        y y y )N
encryptionencrypted_vmotionTencrypted_ftdisabledftEncryptionDisabledopportunisticftEncryptionOpportunisticrequiredftEncryptionRequired)r]   r   migrateEncryptionrY   rW   ftEncryptionMode)r$   r   r%  r&  encrypted_ft_cfgs        r%   configure_encryption_paramsz)PyVmomiHelper.configure_encryption_params  s     KK56IJ(~!2fmm6U6U!U'+$4E1{{<0@#z)#9 0#> +#9 ~!1V]]5S5S!S'+$3C0 "T $r'   c                     g }|||S |j                   j                  j                  D ]   }t        ||      s|j	                  |       " |S r   )r   r   r   rI   r   )r$   rb   r   device_listr   s        r%   get_device_by_typez PyVmomiHelper.get_device_by_type  sU    :ii((// 	+F&$'""6*	+ r'   c                 l    | j                  |t        j                  j                  j                        S N)rb   r   )r3  r   rb   r   VirtualCdromra   s     r%   r   z"PyVmomiHelper.get_vm_cdrom_devices  s&    &&"366==3M3M&NNr'   c                 l    | j                  |t        j                  j                  j                        S r5  )r3  r   rb   r   r   ra   s     r%   r   z PyVmomiHelper.get_vm_ide_devices  s&    &&"366==3U3U&VVr'   c                 l    | j                  |t        j                  j                  j                        S r5  )r3  r   rb   r   r   ra   s     r%   r   z!PyVmomiHelper.get_vm_sata_devices  s&    &&"366==3V3V&WWr'   c                 l    | j                  |t        j                  j                  j                        S r5  )r3  r   rb   r   VirtualNVDIMMControllerra   s     r%   get_vm_nvdimm_ctl_devicez&PyVmomiHelper.get_vm_nvdimm_ctl_device  s&    &&"366==3X3X&YYr'   c                 l    | j                  |t        j                  j                  j                        S r5  )r3  r   rb   r   VirtualNVDIMMra   s     r%   get_vm_nvdimm_devicesz#PyVmomiHelper.get_vm_nvdimm_devices  s&    &&"366==3N3N&OOr'   c                 J   | j                   d   d   r| j                   d   d   dk(  r.| j                   d   d   s| j                  j                  d       |ry|j                  j                  sc|j
                  j                  t        j                  j                  k7  r2| j                  j                  s| j                  j                  d       d}|r|j                  j                  s| j                  |	      }t        |      d
k7  rd}|d
   j                  }| j                   d   d   | j                  |	      }t        |      d
k7  rc| j                  j!                  | j                   d   d   |      }|3| j                   d   d   dk(  rI| j                  j#                  |      }d| _        | j&                  j(                  j+                  |       n|j,                  | j                   d   d   k  rZ| j                  j/                  || j                   d   d         }d| _        | j&                  j(                  j+                  |       n\|j,                  | j                   d   d   kD  r=| j                  j                  d| j                   d   d   d|j,                  d       |-|rg|j                  j                  sO| j                   d   d   ;| j                   d   d   dk(  r$d}	| j1                         r`d}
t3        | j                        }|j5                  |
      }|| j                  j                  d|
z         |j6                  j8                  }	|sU| j                  j;                         }| j&                  j(                  j+                  |       |j<                  j                  }| j                  j?                  |	| j                   d   d         }d| _        | j&                  j(                  j+                  |       yyyyyy)z~
        Manage virtual NVDIMM device to the virtual machine
        Args:
            vm_obj: virtual machine object
        nvdimmr{   r   labelzhPlease specify the label of virtual NVDIMM device using 'label' parameter when state is set to 'absent'.rf   zFVM is not in power off state, can not do virtual NVDIMM configuration.Fr   r   TN)nvdimm_labelnvdimm_devices)nvdimm_devicesize_mb)rD  nvdimm_sizez%Can not change NVDIMM device size to z, MB, which is smaller than the current size z MB.r   z&Host-local PMem Default Storage Policy)profile_namez0Can not find PMem storage policy with name '%s'.)nvdimm_ctl_dev_keypmem_profile_idnvdimm_dev_size_mb) r]   rU   rt   r   r   rq   rr   r   r   r   r   r;  r;   r   r>  rV   find_nvdimm_by_labelremove_nvdimmrY   rW   r   r   capacityInMBupdate_nvdimm_config
is_vcenterr   find_storage_profile_by_name	profileIduniqueIdcreate_nvdimm_controllerr   create_nvdimm_device)r$   r   nvdimm_ctl_exists
nvdimm_ctlnvdimm_ctl_keyrC  existing_nvdimm_devnvdimm_remove_specnvdimm_config_specvc_pmem_profile_idstorage_profile_namespbmpmem_profilenvdimm_ctl_specnvdimm_dev_specs                  r%   configure_nvdimmzPyVmomiHelper.configure_nvdimm  s    ;;x ){{8$W-9$++hBWX_B`%% +L% M fmm44>>,,0L0L0W0WW`d`k`k`v`vKK)).v)w %fmm44!::f:E
z?a'(,%%/]%6%6N{{8,W5A)-)C)Cv)C)N~.!3262D2D2Y2Y-1[[-B7-K/= 3Z 3/  3>#';;x#8#AX#M9=9K9K9Y9Y6I :Z :&$6 <@D$8$(OO$@$@$G$GHZ$[':'G'G$++V^J_`iJj'j=A=O=O=d=d:M8<H8Mi8X >e >*(: @D(<(,(D(D(K(KL^(_)<)I)IDKKX`LabkLl)l(,(=(=EI[[QYEZ[dEeEXEeEeCg(= )h
 ~&1G1GDKKX`LabiLjLr;;x(1Y>)-&(/W,#DKK0'+'H'HVj'H'k'/ KK116hk61  A-9-C-C-L-L*,*.*<*<*U*U*W44;;OL)8)?)?)C)C&*&8&8&M&M+9(:+/;;x+@+K 'N 'O
 ,0D(OO0077H- ? Ms1G&] *r'   c                     g }||S |j                   j                  j                  D ]I  }| j                  j                  j                         D ]   }t        ||      s|j                  |       " K |S r   )r   r   r   rV   nic_device_typevaluesrI   r   )r$   rb   r2  r   device_types        r%   get_vm_network_interfacesz'PyVmomiHelper.get_vm_network_interfaces  su    :ii((// 	/F#11AAHHJ /fk2&&v./	/
 r'   c           
      <	   t               }| j                  d   D ]~  }d|vr d|vr| j                  j                  d       d|v r?| j                  j                  |d         !| j                  j                  d|z         nd|v r| j                  j                  | j                  t        j                  j                  g      }|D ]P  }t        |j                  j                  d      rt        |j                  j                  j                  j                   t"              r]t%        |j                  j                  j                  j                         t%        |d         k(  r|j                  j&                  |d<    nd|v r]|j                  j(                  j&                  |d   k(  r7|j                  j&                  |d   k(  r|j                  j&                  |d<    nY|j                  j&                  |d   k(  s8|j                  j&                  |d<    n  | j                  j                  d|z         d	|v rV|d	   d
vr| j                  j                  d|z         |d	   dk7  r;d|v sd|v r3| j                  j                  d|z         nd|v sd|v rd|d	<   nd|d	<   |j+                  d	      dk(  rHd|v r d|vr| j                  j                  d       d|vr d|v r| j                  j                  d       d|v rV|d   d
vrb| j                  j                  d|z         |d   dk7  r;d|v sd|v r3| j                  j                  d|z         nd|v sd|v rd|d<   nd|d<   |j+                  d      dk(  rHd|v r d|vr| j                  j                  d       d|vr d|v r| j                  j                  d       d|v r|d   | j,                  j.                  j1                         vrW| j                  j                  d|d   ddj3                  | j,                  j.                  j1                               d       d|v r0t5        |d         s"| j                  j                  d |d   z         |j7                  |        |S )!z
        Sanitize user provided network provided params

        Returns: A sanitized list of network params, else fails

        r    r+   vlanzLPlease specify at least a network name or a VLAN name under VM network list.rf   z"Network '%(name)s' does not exist.dvswitch_namezVLAN '%(vlan)s' does not exist.r   )dhcpstaticzZNetwork type '%(type)s' is not a valid parameter. Valid parameters are ['dhcp', 'static'].rk  ipnetmaskzWStatic IP information provided for network "%(name)s", but "type" is set to "%(type)s".rj  zA'netmask' is required if 'ip' is specified under VM network list.zA'ip' is required if 'netmask' is specified under VM network list.typev6zeNetwork type '%(typev6)s' for IPv6 is not a valid parameter. Valid parameters are ['dhcp', 'static'].ipv6	netmaskv6z]Static IPv6 information provided for network "%(name)s", but "typev6" is set to "%(typev6)s".zE'netmaskv6' is required if 'ipv6' is specified under VM network list.zE'ipv6' is required if 'netmaskv6' is specified under VM network list.re  zDevice type specified 'z:' is not valid. Please specify correct device type from ['', ''].maczGDevice MAC address '%s' is invalid. Please provide correct MAC address.)listr]   rU   rt   r^   r>   r   r   r   dvsDistributedVirtualPortgroupr2   r   defaultPortConfigrI   rh  vlanIdr   strr+   distributedVirtualSwitchr   rV   rc  keysjoinr	   r   )r$   network_devicesnetworkdvpsdvps        r%   sanitize_network_paramsz%PyVmomiHelper.sanitize_network_params  s    &{{:. T	,GW$w)>%% +P% Q  TZZ%;%;GFO%L%T%%*NQX*X%Y7"zz..t||cgg>a>a=bc [Cszz;;VD&szz'C'C'H'H'O'OQTU

 < < A A H HISQXY_Q`Maa*-**//&'1JJ??DDP_H``JJOOwv>*-**//zz'&/9*-**//[  KK)).ORY.Y)Z 6?*<<KK)) /Z\c/d) e6?h.DGOyT[G[KK)) /RT[/\) ]
 7?i7&:&.GFO '-GFO{{6"h.7?y'?KK)) /R) Sw&9+?KK)) /R) S 7"8$,>>KK)) /Z\c/d) ex(H4&G:K{^eOe-- 3Z\c3d- e
 W$w(>(0GH% )/GH%{{8$0W$G)CKK)) /R) S([G-CKK)) /R) S 'GM,B$J\J\JlJlJqJqJs,s%%=D]=S=C[[I[I[IkIkIpIpIr=s+u% v wu~(>%% +QSZ[`Sa+b% c ""7+iT	,l r'   c                 j   | j                   d   sy | j                         }| j                  |      }t        |      t        |      k  r3| j                  j                  dt        |      t        |      fz         t        dt        |            D 
]  }d}||   d   }|t        |      k  r|s| j                   d   rt        j                  j                  j                         }t        j                  j                  j                  j                  j                  |_        ||   |_	        d	||   v rP|j                  j                  ||   j                  d	      k7  r%||   j                  d	      |j                  _        d
}d||   v rd|j                  j                   j"                  ||   j                  d      k7  r/||   j                  d      |j                  j                   _        d
}d||   v rd|j                  j                   j$                  ||   j                  d      k7  r/||   j                  d      |j                  j                   _        d
}d||   v rd|j                  j                   j&                  ||   j                  d      k7  r/||   j                  d      |j                  j                   _        d
}|j                  j(                  j*                  |k7  rd|j                  j(                  j*                  vr||j                  j(                  _        d
}n| j-                  |      }t        |      dk(  r|d   }	n&t/        | j0                  t        j2                  g|      }	|	7|j                  j4                  j6                  j8                  |	j:                  k7  r||j                  j(                  _        d
}d||   v rf| j<                  j>                  j                  ||   d         }
tA        |j                  |
      s%| j                  j                  d||   d   z         d||   v r|j                  jB                  ||   jB                  k7  r| j                  j                  d|j                  jB                  z         nz||   j                  dd      }| j<                  jE                  |d|dz   z  ||         }t        j                  j                  j                  j                  jF                  |_        d
}| jH                  jK                  |      }tM        |d      r(d }d||   v rm||   d   }tO        | j0                  |      }|| j                  j                  d|z         tQ        ||      }|| j                  j                  d|z         ne| j-                  |      }t        |      dk(  r|d   }n@| jH                  j/                  | j0                  t        jR                  j2                  g|      }|jT                  jV                  s)| j                  j                  d|jX                  z         |j                  j4                  rtM        |j                  j4                  d      r|j                  j4                  j6                  j8                  |j:                  k7  sK|j                  j4                  j6                  jZ                  |jT                  jV                  j\                  k7  rd
}t        jR                  j_                         }|j:                  |_        | j                   j                  d      }|r||jT                  jV                  jT                  j`                  D cg c]"  }|jT                  j`                  jX                  $ c}vr-| j                  j                  d|d|jX                  d       |jT                  jV                  j\                  |_-        t        j                  j                  jb                  je                         |j                  _        ||j                  j4                  _        ntA        |t        jf                        rt        j                  j                  jb                  ji                         |j                  _        |j*                  jj                  }d |j                  j4                  _6        ||j                  j4                  _5        d!|z  |j                  j(                  _        d
}ntA        |j                  j4                  t        j                  j                  jb                  jn                        sCt        j                  j                  jb                  jo                         |j                  _        d
}|j                  j4                  jp                  |k7  r||j                  j4                  _8        d
}|j                  j4                  jr                  |k7  r||j                  j4                  _9        d
}|s	tA        |t        jf                        r&| jt                  jv                  jy                  |       n%| jz                  jv                  jy                  |       d
| _>        
 y c c}w )"Nr    r   zmGiven network device list is lesser than current VM device list (%d < %d). Removing interfaces is not allowedrf   r   Fr+   r   wake_on_lanTstart_connected	connectedallow_guest_controlDVSwitchr9   re  ziChanging the device type is not possible when interface is already present. The failing device type is %srs  zhChanging MAC address has not effect when interface is already present. The failing new MAC address is %svmxnet3zNetwork Adapter %sportKeysri  z,Unable to find distributed virtual switch %sz(Unable to find distributed port group %sa  Failed to find distributed virtual switch which is associated with distributed virtual portgroup '%s'. Make sure hostsystem is associated with the given distributed virtual portgroup. Also, check if user has correct permission to access distributed virtual switch in the given portgroup.portesxi_hostnamezIt seems that host system 'z8' is not associated with distributed virtual portgroup 'zV'. Please make sure host system is associated with given distributed virtual portgroupznsx.LogicalSwitchznsx.LogicalSwitch: %s)?r]   r  rf  r;   rU   rt   r   r   rb   r   r   r   r   r   wakeOnLanEnabledr   connectablestartConnectedr  allowGuestControl
deviceInforp   r:   r   r   rv  backingr  portgroupKeyr   rV   rc  rI   
macAddress
create_nicaddr^   r>   r2   r   r   ru  r   rz  r+   
switchUuiduuidPortConnectionrE   VirtualEthernetCard!DistributedVirtualPortBackingInfoOpaqueNetworkOpaqueNetworkBackingInfoopaqueNetworkIdopaqueNetworkTypeNetworkBackingInfor~  
deviceNamerX   r   r   rW   rY   )r$   r   r}  current_net_devicesr   nic_change_detectedr=   nicpgspgr   re  net_objpg_objdvs_namedvs_objr    dvs_port_connectionhost_systemrE   
network_ids                        r%   configure_networkzPyVmomiHelper.configure_networkq  s   {{:&668 #<<<G#&9"::KK!! 'K),_)=sCV?W(X'Y! Z C01 P	,C"'*3/7LS,--6T[[=T ffmm557 # ? ? I I N N05
 OC$88::../#2F2J2J=2YY2A#2F2J2J=2YCJJ/*.'$(<<::))88OC<P<T<TUf<gg<KC<P<T<TUf<gCJJ**9*.'/#"66::))33s7K7O7OP[7\\7Fs7K7O7OP[7\CJJ**4*.'(OC,@@::));;s?S?W?WXm?nn?Ns?S?W?WXm?nCJJ**<*.'::((00L@!)>)>)F)FF8D

--5.2+"77Es8q=!$QB!)$,,9X9X8Y[g!hB:););)@)@)M)MQSQWQW)W<HCJJ11926/ OC$88!//??CCOTWDXYfDghF%cjj&9-- 3\4CC4H4W3X- Y OC00SZZ5J5JNabeNfNqNq5qKK)) /RTWT^T^TiTi/j) k
 .c266}iP((33K4HCRSG4T4CC4HJ !$ ? ? I I M M&*#jj,,\:Gw
+"oc&::.s3ODH.t||XFG--2`ck2k-l/FF~--2\_k2k-l#88FH8})!)!!%!4!4T\\CGGDgDgChjv!w }}==KK))c !++	& *  ::%%

 2 2F;

**//<<

J::--22==!==AAFFG +/'&)gg&<&<&>#39::#0 #kkooo>;Y_YfYfYY  ZG  ZG  ZL  ZL  7MQUt{{7G7G7L7L  7M  $MKK))]hjpjuju/w) x 281W1W1\1\#.%(VV]]%F%F%h%h%j

"*=

""'GS%6%67%(VV]]%F%F%_%_%a

"$__<<
7J

""45?

""20G*0T

%%-&*# "#**"4"4cffmm6W6W6j6jk),)J)J)])])_CJJ&*.'::%%--818CJJ&&.*.'::%%00L@4@CJJ&&1*.'" gs'8'89MM..55c:OO0077<'+$aP	,T 7Ms   	'j0c                     t         j                  j                         }|j                  d      |_        |j                  d      |_        |j                  d      |_        |j                  d      |_        |j                  d      |_        |j                  dd      |_	        |j                  dd	      |_
        |j                  d
      |_        |j                  dd      |_        |j                  d      |_        |S )NclassId
instanceIdidcategoryrA  r   stringuserConfigurableTdefaultValuevalue description)r   vAppPropertyInfor   r  r  r  r  rA  r   r  r  r  r  )r$   property_specproperty_infos      r%   set_vapp_propertiesz!PyVmomiHelper.set_vapp_properties  s    --/ - 1 1) <#0#4#4\#B (,,T2!.!2!2:!>+//8*..vx@)6):):;Mt)T&%2%6%6~%F"+//<$1$5$5m$D!r'   c           
         | j                   d   sy | j                   d   D ]0  }|j                  d      r| j                  j                  d       2 t        j
                  j                         }|r|j                  j                  }||j                  ng }t        d |D              }t        d | j                   d   D              }|D cg c]  }|j                   }}|rt        |      dz   nd}	|j                         D ]+  \  }
}d	}t        j
                  j                         }|
|v r|j                  d
      dk(  rd|_        ||
   j                  |_        d}nd|_        ||
   |_        	 |j                         D ]>  \  }}|d
k(  rt%        |j"                  |      |k7  s&t'        |j"                  ||       d}@ nL|j                  d
      dk(  rd|_        | j-                  |      }||_        |	|j"                  _        |	dz  }	d}|s|j                  j/                  |       . n|j                  D cg c]  }|j                   }}|rt        |      dz   nd}	t        d | j                   d   D              }d	}|j                         D ]x  \  }
}t        j
                  j                         }d|_        | j-                  |      }||_        |	|j"                  _        |	dz  }	d}|s^|j                  j/                  |       z |j                  r|| j0                  _        d| _        y y c c}w # t(        $ r;}dddt+        |      }| j                  j                  |       Y d }~nd }~ww xY wc c}w )Nvapp_propertiesr  z#id is required to set vApp propertyrf   c              3   8   K   | ]  }|j                   |f  y wr   )r  .0r7   s     r%   	<genexpr>z:PyVmomiHelper.configure_vapp_properties.<locals>.<genexpr>/  s     *NADD!9*Ns   c              3   *   K   | ]  }|d    |f  ywr  NrP   r  s     r%   r  z:PyVmomiHelper.configure_vapp_properties.<locals>.<genexpr>0       ,baagq\,b   r9   r   Fr   removeTr   z#Failed to set vApp property field='z' and value='z
'. Error: r  c              3   *   K   | ]  }|d    |f  ywr  rP   r  s     r%   r  z:PyVmomiHelper.configure_vapp_properties.<locals>.<genexpr>j  r  r  )r]   r   rU   rt   r   r  VmConfigSpecr   
vAppConfigpropertydictr   r  r1   PropertySpecr   	removeKeyrz   getattrsetattr	Exceptionr
   r  r   rW   rY   )r$   r   r7   new_vmconfig_spec	orig_specorig_propertiesvapp_properties_currentvapp_properties_to_changeall_keysnew_property_indexproperty_idr  is_property_changednew_vapp_property_specproperty_nameproperty_valuer}   rg   r  s                      r%   configure_vapp_propertiesz'PyVmomiHelper.configure_vapp_properties   s   {{,-./ 	QA55;%%*O%P	Q  HH11300I4=4Ii00rO&**No*N&N#(,,b4;;O`Ca,b(b% (77!7H76>X!2A.G.M.M.O .N*]&+#),)>)>)@&"99$((5A;C.8;RS^;_;c;c.8.2+ <B.86Mk6Z.3;ANATATAV 
? =~#0K#? %- $++A+F+F#VZh#h$+,B,G,GXf$g:>$7
?  %((5A  8=*4 %)$<$<]$KM2?*/6H*//3&!+&*.'&%..556LM].Nb (9'A'AB!BHB6>X!2A(,,b4;;O`Ca,b(b%"'.G.M.M.O N*]),)>)>)@&38&0 !% 8 8 G.;&+2D&++/"a'"&*#&%..556LMN  %%):DOO&#'D  &S 8:  ) ;hu  xF  HO  PQ  HR  #SC KK11c1::;. Cs*   L=55M+MN		N0NNc                    | j                   d   sy |}g |_        d}| j                  |      }| j                   d   D ]  }d|vsd|vr| j                  j	                  d       t        |d   t        t        f      rCt        |d         j                         }|d   j                  |d   d      j                         }n|d   }|d   j                  |d   d      }|d   |d   vr|d   dk7  s||k7  rLt        j                  j                         }	|d   |	_        ||	_        |j                  j!                  |	       d}|sd| _         y )	Nadvanced_settingsFr   r  z?advanced_settings items required both 'key' and 'value' fields.rf   r  T)r]   extraConfigrc   rU   	exit_jsonrI   r  r   ry  upperr   r   optionOptionValuer   r  r   rY   )
r$   r   config_specvm_custom_specrj   factskvspecifiedvaluecomparisonvaluer  s
             r%   customize_advanced_settingsz)PyVmomiHelper.customize_advanced_settings  sT   {{./$%'"!!&)++12 	,BB'"3%%*k%l "W+c{3!$R[!1!7!7!9"'(;"<"@"@EB"O"U"U"W!#G"'(;"<"@"@EB"O5	':!;;7r@QVeiwVw//1Y
-**11&9'+$+	,r'   c                    | j                   d   sy | j                         s| j                  j                  d       y | j	                  |      }| j                   d   D ]  }d|vsd|vr| j                  j                  d       d }| j                  j                  j                  D ]"  }|j                  |d   k(  s|j                  } n |s"| j                  j                  d|d   z         |d   |d   vs|d   |d      |d   k7  s| j                  j                  j                  |||d          d	| _         y )
Ncustomvaluesz`Currently connected to ESXi. customvalues are a vCenter feature, this parameter will be ignored.r   r  z:customvalues items required both 'key' and 'value' fields.rf   z"Unable to find custom value key %s)entityr   r  T)r]   rO  rU   warnrc   r  r   customFieldsManagerfieldr+   r   rt   SetFieldrY   )r$   r   r  r  key_idr  s         r%   customize_customvaluesz$PyVmomiHelper.customize_customvalues  sH   {{>* KK c d!!&)++n- 	,BB'"3%%*f%gF99?? ::E*"YYF
 %%*NQSTYQZ*Z%[ %yn 55~9NrRWy9Y]_`g]h9h0099V[]^e[f9g'+$!	,r'   c                    | j                   j                  d      }|rk| j                  j                  }|j	                  |      r$|j                  |      }|j                  | _        y | j                  j                  d|z         g }| j                   d   D ]  }t        j                  j                  j                         }t        j                  j                  j                         |_        d|v rd|v r|t        j                  j                  j!                         |j                  _        t%        |d         |j                  j"                  _        t%        |d         |j                  _        nCd|v r?|d   d	k(  r7t        j                  j                  j+                         |j                  _        d
|v rd|v rt        j                  j                  j                  j-                         |j                  _        t        j                  j                  j1                         g|j                  j.                  _        t%        |d
         |j                  j.                  j"                  d   _        t3        |d         |j                  j.                  j"                  d   _        nd|v r|d   d	k(  rt        j                  j                  j                  j-                         |j                  _        t        j                  j                  j5                         g|j                  j.                  _        d|v r|d   |j                  _        d|v r|d   |j                  j.                  _        d|v r|d   |j                  _        n3| j                   d   d   !| j                   d   d   |j                  _        d|v r|d   |j                  _        n3| j                   d   d   !| j                   d   d   |j                  _        |j=                  |        t        j                  j                  j?                         }| j                   d   d   | j                   d   d   |_        g }	| j                   d   d   }
|
r.tA        |
tB              r|	|
z  }	n|	j=                  |
       |	|_"        | j                   d   d   )|	jG                  d| j                   d   d          |	|_"        | j                   d   | j                   d   }n |jH                  jJ                  jL                  }d|v rt        j                  j                  jO                         }t        j                  j                  jQ                         |_)        t        j                  j                  jU                         |jR                  _+        d}d| j                   v r/| j                   d   r | j                   d   jY                  dd      }n|r|jZ                  jY                  dd      }t\        j^                  jY                  dd      }dja                  |D cg c]	  }||vs| c}      }| j                   d   d   /| j                   d   d   dd |jR                  jV                  _-        n|dd |jR                  jV                  _-        t%        | j                   d   j                  dd            |jR                  _1        t%        | j                   d   j                  dd            |jR                  _2        | j                   d   d    *t%        | j                   d   d          |jR                  _3        t        j                  j                  ji                         |_5        | j                   d   d!   O| j                   d   d!   |jj                  _6        | j                   d   j                  d"d#      |jj                  _7        | j                   d   d$   ;| jp                  js                  | j                   d   d$   d%      |jj                  _:        t        j                  j                  jw                         |_<        | j                   d   d&   | j                   d   d&   dk(  rd |jj                  _=        nt        j                  j                  j}                         |jj                  _=        t%        | j                   d   d&         |jj                  jz                  _?        d'|jj                  jz                  _@        | j                   d   d(   !| j                   d   d)   | j                   d   d*   | j                  j                  d+       | j                   d   d)   |jx                  _A        | j                   d   d(   |jx                  _B        t        j                  j                  j}                         |jx                  _C        | j                   d   d*   |jx                  j                  _?        d'|jx                  j                  _@        | j                   d   d,   |jx                  _D        n3| j                   d   d-   !| j                   d   d-   |jx                  _E        | j                   d   d.   t        j                  j                  j                         |_G        | j                   d   d.   |j                  _H        nt        j                  j                  j                         }| j                   d   d   | j                   d   d   |_J        t        j                  j                  jU                         |_K        d}d| j                   v r| j                   d   r| j                   d   }n|r|jZ                  }| j                   d   d   %| j                   d   d   j                  d/      d   }n|j                  d/      d   }t        j                  d0d|      }||j                  _-        | j                   d   d$   | j                   d   d$   |_:        | j                   d   d1   | j                   d   d1   |_O        | j                   d   d2   | j                   d   d2   |_P        t        j                  j                  j                         | _        || j                  _R        || j                  _S        || j                  _T        y c c}w )3Ncustomization_spec)r+   zGUnable to find customization specification '%s' in given configuration.rf   r    rl  rm  r   rj  ro  rp  r   rn  gateway	gatewayv6domaincustomizationdns_servers
dns_suffixr   winr  r+    r  hostname   fullnameAdministratororgnameACME	productid	autologonautologoncountr9   timezonezcustomization.timezonepasswordT
joindomaindomainadmindomainadminpasswordzr'domainadmin' and 'domainadminpassword' entries are mandatory in 'customization' section to use joindomain feature	domain_oujoinworkgrouprunonce.z[^a-zA-Z0-9\-]
hwclockUTCscript_text)Ur]   r   r   customizationSpecManagerDoesCustomizationSpecExistGetCustomizationSpecspecr\   rU   rt   r   rb   r  AdapterMapping
IPSettingsadapterFixedIprl  ry  	ipAddress
subnetMaskDhcpIpGeneratorIpV6AddressSpecipV6Spec	FixedIpV6r   DhcpIpV6Generatorr  	dnsDomaindnsServerListr   GlobalIPSettingsrI   rt  dnsSuffixListinsertrp   r   r   SysprepUserDatauserData	FixedNamecomputerNamereplacer+   r  punctuationr|  fullNameorgName	productIdGuiUnattendedguiUnattended	autoLogonautoLogonCountrV   integer_valuetimeZoneIdentificationidentificationr  Passwordr  	plainTextdomainAdmin
joinDomaindomainAdminPassworddomainOUjoinWorkgroup
GuiRunOnce
guiRunOncecommandList	LinuxPrepr  hostNamer  resub
hwClockUTC
scriptTextSpecificationnicSettingMapglobalIPSettingsidentity)r$   r   custom_spec_namecc_mgr	temp_specadaptermapsr~  	guest_mapglobalipdns_suffixesr  r   identdefault_namer/  cr  valid_hostnames                     r%   customize_vmzPyVmomiHelper.customize_vm  s
     ;;??+?@\\::F006F0G"77=M7N	"+..KK!! 'FHX'Y! Z {{:. '	*G,,;;=I # 4 4 ? ? AIw9#7'*vv';';'C'C'E	!!$14WT]1C	!!$$./2793E/F	!!,7"wv&'@'*vv';';'K'K'M	!!$ [G%;-0VV-A-A-L-L-\-\-^	!!*141E1E1O1O1Q0R	!!**-=@=Q	!!**--a0:>A'+BV>W	!!**--a0;W$):f)D-0VV-A-A-L-L-\-\-^	!!*141E1E1W1W1Y0Z	!!**-G#,3I,>	!!)g%5<[5I	!!**2 7".5h.?	!!+_-h7C.2kk/.J8.T	!!+'29-2H	!!/_-m<H26++o2N}2]	!!/y)O'	*T 66''88:;;'6B%)[[%A-%PH" [[1,?
*d+
*##J/%1H";;'1=4;;#?#IJ%1H";;z".{{:.H~~,,44H HFF((002E VV11::<EN +.&&*>*>*H*H*JENN'L$V)<#{{62::3C%{{223; ,,44S"=K77|#T!q?SA#TUL{{?+J7C37;;3OPZ3[\]^`3a++03?"3E++0&)$++o*F*J*J:Wf*g&hENN#%(_)E)I)I)U[)\%]ENN"{{?+K8D+.t{{?/KK/X+Y("%&&"6"6"D"D"FE{{?+K8D04O0L[0Y##-59[[5Q5U5UVfhi5j##2{{?+J7C/3/A/A/O/OKK0<,0.##, $'66#7#7#F#F#HE {{?+J7?4;;C_`jCkoqCq/3##,/2vv/C/C/L/L/N##,58_9UV`9a5b##,,29=##,,6{{?+L9E;;/>F$++VeJfg|J}  KFKK)) /C) D 48;;3OP]3^$$026++o2N|2\$$/;>66;O;O;X;X;Z$$8AE_A]^sAt$$88>EI$$88B 15O0L[0Y$$-_-o>J59[[5QRa5b$$2{{?+I6B#&66#7#7#B#B#D /3{{?/KI/V  , FF((224E {{?+H5A#{{?;HE VV11;;=ENL$V)<#{{62%{{{{?+J7C;;7
CII#NqQ'--c215  VV$5r8DN"0ENN {{?+J7C!%_!=j!I{{?+L9E#';;#?#M {{?+M:F#';;#?#N &&..<<>(3%+3(#( } $Us   	ttc                    g }|y |j                   j                  j                  D ]^  }| j                  j	                  |      st
        j                  j                  j                         }||_        |j                  |       ` |S r   )	r   r   r   rV   is_scsi_controllerr   rb   r   r   )r$   r   	scsi_ctlsr   scsi_ctls        r%   get_vm_scsi_controllersz%PyVmomiHelper.get_vm_scsi_controllers~	  su    	>mm,,33 	+F!!44V<66==::<"(  *		+ r'   c                    |j                         D cg c]!  }|j                  d      s|dk(  s||   s |# c}rQ|d   rt        j                  d      }|j	                  |d         }	 |r#|j                  d      }|j                  d      }nt        t        j                  d|      rt        |      }nt        |      }|r|st        nR|j                         D cg c]  }|j                  d      s||   s| c}d	   }|j                  d
      d   }||   }t        dddd	      }|v r|j                         }d||   z  z  S | j                  j                  |ddj!                  |j                               d       | j                  j                  d       y c c}w # t        t        t        f$ r | j                  j                  d       Y w xY wc c}w )Nsize_sizez(\d+(?:\.\d+)?)([tgmkTGMK][bB])r9   r   z\d+\.\d+zKFailed to parse disk size please review value provided using documentation.rf   r   _r     )tbgbmbkb   z> is not a supported unit for disk size. Supported units are ['rq  rr  zKNo size, size_kb, size_mb, size_gb or size_tb defined in disk configuration)r{  
startswithrG  compilematchgroupr  floatr   	TypeError	NameErrorrU   rt   r  r  rs   r|  )	r$   expected_disk_specr7   
size_regexdisk_size_mexpectedunitparam
disk_unitss	            r%   get_configured_disk_sizez&PyVmomiHelper.get_configured_disk_size	  s   )..0u!Q\\'5JaSYk_qrs_tAu!&)ZZ(JK
(../A&/IJP"#.#4#4Q#7*003((xxX6#(? $'x=#4(( ,0 %7$;$;$=qqgAV[mno[pqrst{{3'+-e4qQ15Jz!zz|4:d+;#;<<%%LPLRKKXbXgXgXiLj+l% m
 	] 	 	_S v, ":y9 PKK)) /O) PP
 rs4   F+F+F+,A"F0 !G&8G&>G&00G#"G#c                    |d   }|r#|j                   j                  j                  |k7  s|Y||j                   j                  _        d|j                   _        d| _        | j
                  j                  j                  |       yy)z
        Adds vmdk file described by expected_disk_spec['filename'], retrieves the file
        information and adds the correct spec to self.configspec.deviceChange.
        filenameNr  T)r   r  fileNamer   rY   rW   r   r   )r$   r   rq  diskspecr^  rz  s         r%   add_existing_vmdkzPyVmomiHelper.add_existing_vmdk	  sq    
 &j1x..778C/7HOO##,"$HOO#'D OO((//9	 IWr'   c                 h   g }| j                   j                  d      D ]  }|d   
|d   |d   | j                  j                  d       |d   }|d   }||d<   |d   }t	        |      dk7  r)d}|D ]  }|d	   | j
                  j                  j                         v r_|| j
                  j                  j                         v r9|d	   |k7  r1|d
   |k(  r)| j                  j                  d|d	   d|d|d       |d	   |k(  s|d
   |k(  st        dt	        |d               D ]7  }	|d   |d   |	   d   k(  s| j                  j                  d|d|d       9 |d   j                  |       d} n |rc|j                  |||gd       {|j                  |||gd        |S )a  

        Sanitize user provided disk parameters to configure multiple types of disk controllers and attached disks

        Returns: A sanitized dict of disk params, else fails
                 e.g., [{'type': 'nvme', 'num': 1, 'disk': []}, {}, {}, {}]}

        diskr   r   r   z'disk.controller_type', 'disk.controller_number' and 'disk.unit_number' are mandatory parameters when configure multiple disk controllers and disks.rf   r   Fr   numzSpecified SCSI controller 'z' and 'z' have the same bus number: ''z[Specified the same 'controller_type, controller_number, unit_number in disk configuration ':T)r   r  r  )
r]   r   rU   rt   r;   rV   scsi_device_typer{  r   r   )
r$   r   controllers	disk_specr   ctl_unit_numr   r   ctlis
             r%   sanitize_disk_parametersz&PyVmomiHelper.sanitize_disk_parameters	  s    0 	\I*+3yAT7U7]ajkxay  bB%% +v% w   34G$]3L'3Im$ !23H;1$!	& C6{d&8&8&I&I&N&N&PPU]aeasas  bE  bE  bJ  bJ  bL  VLv;(2s5zW7L KK11BEf+xY`7b1 c 6{h.3u:3H!&q#c&k*:!; }A(73v;q>-;XX $ 5 5iqsz;| 5 !}} F**95$(	 !&&S\R]'^_""HWyk#Z[=	\@ r'   c                    d}|d   rp|j                  d      }|rA|j                  j                  j                  |k7  rW||j                  j                  _        d}n9||j                  j                  _        n|sd|j                  j                  _        |sS|j                  dd      }|dk(  rd|j                  j                  _        n |dk(  rd|j                  j                  _        | j                  |      }|r||j                  j                  |kD  r5| j                  j                  d||j                  j                  fz  	       |j                  j                  |k7  r||j                  _        d}|S ||j                  _        d}|S )
NF	disk_modeT
persistentr   thineagerzeroedthickzNGiven disk size is smaller than found (%d < %d).Reducing disks is not allowed.rf   )
r   r   r  diskModethinProvisionedeagerlyScrubrx  capacityInKBrU   rt   )r$   r  rq  reconfiguredisk_modifiedr  	disk_typerh  s           r%   set_disk_parametersz!PyVmomiHelper.set_disk_parameters	  sw   k**..{;I##++44	A8AI$$,,5$(M4=	  ((10<I$$-*..vv>IF";?	  ((8008<	  ((5**+=>,,r1%% +KNPR[RbRbRoRoMp+q% r,,202	  - $
  -/I) Mr'   c                 :   | j                  |      }t        |      dk(  ry |D ]  }| j                  j                  ||d   |d         \  }}||d   | j                  j                  j                         v r^|\| j                  |      }|rI|D ]D  }|j                  j                  |d   k(  s | j                  j                  d|d   d|       F | j                  j                  |d   |d         }d| _        | j                  j                  j                  |       n/t         j"                  j                  j%                         }||_        t'        dt        |d               D ]  }	d }
d }d	}d	}d	}|d   |	   d
   }t        |      dk7  r|D ]  }|j(                  |k(  s|}
d} n |rt         j"                  j                  j%                         }t         j"                  j                  j$                  j*                  j,                  |_        |
|_        | j1                  ||d   |	   d      }t        |      dk(  s|sq| j                  j3                  ||      }
t         j"                  j                  j$                  j4                  j6                  |
_        | j1                  |
|d   |	         }|r,d| _        | j                  j                  j                  |       |s~d| _        | j                  j                  j                  |
         y )Nr   r   r  z"Specified SCSI controller number 'z' is already used by: rf   Tr  Fr   )r  )r  r;   rV   get_controller_disksr  r{  r_  r   r   rU   rt   create_disk_controllerrY   rW   r   r   r   rb   r   r   r   r   r   r   r  create_hard_diskFileOperationcreatefileOperation)r$   r   ctlsr  disk_ctl	disk_listr]  r^  disk_ctl_specj	hard_diskhard_disk_spechard_disk_existdisk_modified_for_specdisk_modified_for_diskdisk_unit_numberr  s                    r%   $configure_multiple_controllers_disksz2PyVmomiHelper.configure_multiple_controllers_disks
  s   ,,V4t9> 3	CC"&"4"4"I"I&RUV\R]_bch_i"jHiv;$"4"4"E"E"J"J"LLQWQc $ < <V DI (1 ^H'88CJF $ 5 5GJ5zS[;] 5 !^^
 !% 2 2 I I#f+WZ[`Wa b'+$,,33MB # ? ? A'/$1c#f+./  C 	!%"').&).&#&v;q>-#@ y>Q& ) "??.>>(,I.2O!	" #%(VV]]%D%D%FN/2vv}}/N/N/X/X/]/]N,,5N)-1-E-EnVYZ`VabcVdrv-E-w*y>Q&o $ 2 2 C CMSc dI.1ffmm.M.M.[.[.b.bI+-1-E-EiQTU[Q\]^Q_-`* *+/D(OO0077G)+/D(OO0077	BA C'3	Cr'   c                 
   | j                   d   sy d}| j                   j                  d      D ]  }|d   s|d   s|d   sd} n |r| j                  |       y | j                  |      }||sW| j                  j                  | j                         d      }d| _        | j                  j                  j                  |       n|d   }|]|j                  j                  j                  D cg c]3  }t        |t        j                   j                  j"                        s2|5 c}nd }|| j                   j                  d      r|t%        | j                   j                  d            t%        |      k  rL| j&                  j)                  dt%        | j                   j                  d            t%        |      fz  	       d}d}	| j                   j                  d      D ]  }
d}||~|t%        |      k  rpt        j                   j                  j+                         }t        j                   j                  j*                  j,                  j.                  |_        ||   |_        n[| j                  j3                  ||	      }t        j                   j                  j*                  j,                  j4                  |_        d}|d
z  }|	d
z  }	|	dk(  r|	d
z  }	|
d   rW|
j                  dd      }|r#|j                  j6                  j8                  |k7  s|9||j                  j6                  _        d}nd|j                  j6                  _        |
d   ra|
j                  dd      j;                         }|dk(  rd|j                  j6                  _        n |dk(  rd|j                  j6                  _        |
d   r| jA                  ||
||       |j                  j6                  jB                  dk(  r=t        j                   j                  j*                  jD                  jF                  |_$        |
j                  d      r	 | jK                  |
      }||j                  jL                  k  r5| j&                  j)                  d||j                  jL                  fz  	       ||j                  jL                  k7  s|s||j                  _&        | j                  j                  j                  |       d| _         y c c}w )Nr  Fr   r   r   Tr   zMProvided disks configuration has less disks than the target object (%d vs %d)rf   r9      r  r  r   r  r  r  rz  	datastorezOGiven disk size is smaller than found (%d < %d). Reducing disks is not allowed.)'r]   r   r  r_  rV   create_scsi_controllerget_scsi_typerY   rW   r   r   r   r   r   rI   r   rb   VirtualDiskr;   rU   rt   r   r   r   r   r  r  r  r  rs   r  r  r}  r{  r  r  r  rx  r  )r$   r   configure_multiple_ctlr  r]  r^  r7   disks
disk_indexdisk_index_scsirq  r  r|  r  r  rh  s                   r%   configure_diskszPyVmomiHelper.configure_disksO
  sP   {{6"
 "'0 	I*+y9L/MQZ[hQi)-&	 "55f= 008	 >))@@ASASAUWXYH#'D OO((//9 |H ! #MM2299fqZ366==KdKd=ef'+ 	 !8SQWAX=Y\_`e\f=fKK!! 'EHKDKKOO\bLcHdfijofpGq'r! s 
"&++//&"9 ?	,!M!e&7JU<S66==::<%(VV]]%D%D%N%N%S%S""'
"3-->>xY%(VV]]%D%D%N%N%R%R" $ !OJq O!#1$!+..22;M	x66??9LRXR`7@HOO++4$(M3?''0 "&).2262>DDF	&>BHOO++;"44;?HOO++8!*-&&v/A8XV &&//25),)H)H)V)V)])]& "%%k2 ../ABBHOO000%%iX__99:; & < X__111]/1,,,33H='+$?	, gs   /3T#Tc                 \   | j                   j                  | j                  d         }|s)| j                  j	                  d| j                  z         |j
                  j                  dk7  s|j
                  j                  r)| j                  j	                  d| j                  z         |S )Nr  z+Failed to find ESX host "%(esxi_hostname)s"rf   r  zDESXi "%(esxi_hostname)s" is in invalid state or in maintenance mode.)r^   rF   r]   rU   rt   rq   connectionStateinMaintenanceMode)r$   
hostsystems     r%   select_hostzPyVmomiHelper.select_host
  s    ZZ,,T[[-IJ
KK!!&SVZVaVa&a!b--<
@R@R@d@dKK!!&losozoz&z!{r'   c                 h   d }| j                   j                  | j                  t        j                  g      }|t        |      dk(  r| j                  j                  d       d}|D ]G  }| j                  |      s|j                  j                  |kD  s0|}|j                  j                  }I |S )Nr   z2Unable to find a datastore list when autoselectingrf   datastore_obj)r^   r   r   r   	Datastorer;   rU   rt   is_datastore_validrp   	freeSpace)r$   r  
datastoresdatastore_freespacedss        r%   autoselect_datastorez"PyVmomiHelper.autoselect_datastore
  s    	ZZ,,T\\CMM?K
ZA!5KK!!&Z![ 	;B***<zz##&99	&(jj&:&:#	; r'   c           	         d }d }| j                   d   r| j                   d   d   d   r)g }| j                   d   r| j                  | j                   d   | j                        }|j                  D ]  }|j                  j
                  j                  j                  D ]  }|j                  j                  dk(  s|j                  j                  dk(  s6|j                  | j                  j                  | j                  t        j                  g|j                  j                                 nc| j                   d   r| j!                  | j                   d         }|j                  j
                  j                  j                  D ]  }|j                  j                  dk(  s|j                  j                  dk(  s6|j                  | j                  j                  | j                  t        j                  g|j                  j                                nz| j                  j#                  | j                  t        j                  g      }|D cg c]:  }| j                  j%                  |      j                  | j                   d   k(  s9|< }}d}	|D ]  }
| j'                  |
	      s|
j(                  j*                  |	kD  s|
j(                  j*                  |	k(  sI|rL| j                   d   d   d
   r2|
j                  j-                  | j                   d   d   d
         dk  r|
}|j                  }|
j(                  j*                  }	 n| j                   d   d   d
   r| j                   d   d   d
   }| j                  j                  | j                  t        j.                  g|      }|r| j1                  |      }| j                  j                  | j                  t        j                  g|      }n| j2                  j5                  d       |s| j                   d   r|j6                  j8                  j:                  D cg c]3  }t=        |t        j>                  j:                  j@                        s2|5 }}|r%|d   jB                  jD                  }|j                  }|rS| j                  j%                  |      }|j                  | j                   d   k7  r| jG                         }|j                  }|srtI        | j                   d         dk7  s| j                   d   ,| j2                  j5                  d| j                   d   z         | j2                  j5                  d       ||fS c c}w c c}w )Nr  r   r  rA   VMFSNFSr  rK   r  r  datastore_cluster_objzOEither datastore or autoselect_datastore should be provided to select datastorerf   r   zUnable to find the datastore with given parameters. This could mean, %s is a non-existent virtual machine and module tried to deploy it as new virtual machine with no disk. Please specify disks parameter or specify template to clone from.r+   z#Failed to find a matching datastore)%r]   find_cluster_by_namer   rE   configManagerstorageSystemfileSystemVolumeInfo	mountInfovolumer   r   r^   r   r   r  r+   find_hostsystem_by_namer   r*   r  rp   r  find
StoragePodget_recommended_datastorerU   rt   r   r   r   rI   rb   r  r  r  r  r;   )r$   r   r  datastore_namer  rA   rE   mir7   r  r  datastore_clusterr  dcs                 r%   select_datastorezPyVmomiHelper.select_datastore
  s   	;;v{{6"1%&<=
;;y)"77I8NPTP\P\]G ' v"&"4"4"B"B"W"W"a"a vB!yy~~7299>>U;R * 1 1$**2E2EdllUXUbUbTcegeneneses2t uvv [[177O8TUD"00>>SS]] r99>>V3ryy~~7N&--djj.A.A$,,QTQ^Q^P_acajajaoao.pqr "&!8!8!WJ-7  "B4::;[;[\];^;c;cgkgrgrs  hA  <A!  "BJ  "B&'#$ CB222D 

,,/BB

H\H\`sHs  }F;;v.q1+>277<<PTP[P[\bPcdePfgrPsCtwxCx$$&	)2.0jj.B.B+C V$Q'4!%V!4Q!7!D$(JJ$7$7s~~FVXf$g!$%)%C%CZk%C%lN JJ//s}}o~^	%%*{%|T[[4 & 6 6 = =j1Asvv}}OhOhAiQjEj!!H,,66	!*ZZ55i@77dkk,77 $ 9 9 ;I%.^^N4;;v&'1,J0G0O%% +P SWR]R]^dRe+f% g KK!!&K!L.((c "B< ks   :U<U<3VVc                     ||
t               |}	 |j                  |j                  k(  ry|j                  }|dv ry|j                  }|y;)NT)zgroup-d1zha-folder-rootF)AssertionErrorr+   _moIdrH   )r$   r/   rH   current_parentmoids        r%   obj_has_parentzPyVmomiHelper.obj_has_parent  sc    ;6> """"fkk1 "''D55+22N% r'   c                 0    | j                   d   d   }||S y)Nr   scsiparavirtual)r]   )r$   disk_controller_types     r%   r  zPyVmomiHelper.get_scsi_type,  s%    #{{:6v>+''r'   c                    |j                  d      D cg c]  }|j                  dd       }}t        |      dz
  }d}| j                  j                  }|r||k  rd}t        |d      r/|j                  D ]  }|j                  ||   k(  s|}|dz  }d} nZ nXt        |t        j                        r<t        |d      r2|j                  j                  ||   k(  r|j                  }|dz  }d}nd	}|sd	}|r||k  r|S c c}w )
zA Walk inventory objects one position of the searchpath at a time /r  r9   r   FchildEntityTvmFolderN)r  r.  r;   r   
rootFolderr2   r  r+   rI   r   rJ   r  )	r$   
searchpathr7   pathspaths_totalpositionrootchangechilds	            r%   find_folderzPyVmomiHelper.find_folder2  s    .8-=-=c-BC3#CC%j1n ||&&x;.Ft]+!-- EzzU8_4$ A!% D#..14,}}))U8_<#}} A!%' x;.* 7 Ds   C?c                    |xs | j                   j                  dd      }|xs | j                   j                  dd      }|xs | j                   j                  dd      }t        | j                  t        j
                  g| j                   d         }|s,| j                  j                  d| j                   d   z         |rJt        | j                  t        j                  g||      }|sz| j                  j                  d	|z         nZ|rVt        | j                  t        j                  g||      }|s| j                  j                  d
|z         |j                  }nd}t        | j                  t        j                  g||xs |      }|s?|r!| j                  j                  d|z         |S | j                  j                  d       |S )zQ Get a resource pool, filter on cluster, esxi_hostname or resource_pool if given rA   Nr  resource_poolrK   zUnable to find datacenter "%s"rf   )folderzUnable to find cluster "%s"zUnable to find host "%s"z!Unable to find resource_pool "%s"zKUnable to find resource pool, need esxi_hostname, resource_pool, or cluster)r]   r   r   r   r   rJ   rU   rt   ComputeResourcerD   rH   ResourcePool)r$   rA   rE   r  cluster_name	host_nameresource_pool_namerK   s           r%   get_resource_poolzPyVmomiHelper.get_resource_poolS  s    B$++//)T"BBDKKOOOTB	*Tdkkooot.T dllS^^,<dkk,>WX
KK!!&FUaIb&b!c t||c.A.A-BLYcdG%%*G,*V%WDLL3>>*:IjYD%%*Dy*P%QkkGG !0@0@/ACU^e^sist!%%*MPb*b%c  %%*w%xr'   c                    | j                   j                  dd       | _        | j                  | j                  j	                  d       | j                  j                  d      sd| j                   z  | _        | j                  j                  d      | _        | j                  j                  | j                  t        j                  g| j                   d         }|)| j                  j	                  d| j                   z         t        |      }|j                  d      s|dz  }| j                  j                  || j                   d   z   dz         s1| j                  j                  |dz   | j                   d   z   dz         r| j                  }n| j                  j                  d	      s| j                  dk(  r || j                   d   | j                  }n\| j                  j                  d      r!|| j                   d   d| j                  }n || j                   d   d	| j                  }| j                  j                  j                  |      }|H|j                   || j                  |d
}| j                  j	                  d| j                  d||       |}| j                   d   r| j#                  | j                   d         }|)| j                  j	                  d| j                   z         | j                   d   |j$                  j&                  j(                  | j                   d   |j$                  j&                  j(                  k7  rP| j                   d   |j$                  j&                  j(                  d}| j                  j	                  d|       nd }| j+                         }| j                   d   r| j                   d   }	| j                  j                  | j                  t        j,                  g|	      }
|
r| j/                  |
      }	| j                  j                  | j                  t        j0                  g|	      }n| j3                  |      \  }}	t        j4                  j7                         | _        g | j8                  _        t        j4                  j=                         | _        g | j>                  _        | jA                  |d       | jC                  |d       | jE                  |       | jG                  |       | jI                  |       | jK                  |       | jM                  |       | jO                  |       | jQ                  |       | jS                  |       d}| j                   d   D ]"  }|D ]  }|dk(  r|d   dk(  rd} |dvsd} " $ tU        d | j                   d   jW                         D              s|s| j                   j                  d       | jY                  |       d }d }	 | j                   d   r| j                   d!   r| j[                         | j>                  _.        || j>                  _/        | j                   d"   r[|j&                  j`                  jb                  D ]7  }te        |t        j4                  jb                  jf                        s3t        j4                  j<                  ji                         }t        j4                  jb                  jf                  jk                         |_6        | j                   d"   d#k(  rd|jl                  _7        | j                   d"   d$k(  rd|jl                  _8        | j                   d"   d%k(  rd&|jl                  _9        |jt                  |_;        ||_/        | j>                  jx                  j{                  |       : || j>                  _>        | j                   j                  d'      }| j                   j                  d(d       }|r\|>t        j4                  j<                  j~                  j                  | j>                  _A        n| j                  j	                  d)       t        j4                  j                  | j                   d*   | j>                  +      }| j                  r| j                  |_D        ||j                  )| j                  j	                  d,| j                   z         | j                  |j                  j                  |-      }t        |      d.k7  r)| j                  j	                  d/| j                   z         |d0   j                  |_E        | j8                  |_        d1}	 |j                  || j                   d2   |3      }d| _N        n| j                   d2   | j8                  _        t        j4                  j                  d d d d7|	z   d8z   9      | j8                  _P        d }| j                   d!   r| j[                         }d:}	 |j                  | j8                  ||;      }d| _N        | j                        }j                  j                  d?k(  r5t        |      }t        | j8                        }| j                  d|||d@}|S |j                  j                  }| j                   dA   rt        j4                  j7                         }t        | j                   dA         |_^        |j                  |      }| j                  |      }|j                  j                  d?k(  r| j                  d|dAdBS | j                   dC   r}t        j4                  j7                         }| j                  ||D       |j                  |      }| j                  |      }|j                  j                  d?k(  r| j                  d|dCdBS | j                   dE   r| j                  |       | j                   dF   s | j                   dG   s| j                   dH   dIv rt        | j                  |dJdK       | j                   dF   r$t        | j                  || j                   dL          | j                   dG   rE| j                  || j                   dM   N      } | s#| j                  |      }!| j                  ddO|!ddPS | j                  |      }!| j                  d|!dQS # t        j                  j                  $ rP}| j                  j	                  d4| j                   d2   d5|d6t        |j                               Y d }~d }~ww xY w# t        j                  j                  $ r=}| j                  j	                  d<t        |j                        z         Y d }~td }~wt        j                  j                  $ r=}| j                  j	                  d=t        |j                        z         Y d }~d }~ww xY w# t        $ r3}| j                  j	                  d>t        |      z         Y d }~d }~ww xY w)RNr  z@Folder is required parameter while deploying new virtual machinerf   r  z/%(folder)srK   z,No datacenter named %(datacenter)s was foundz/vmz/vm/)rK   datacenter_pathr  full_search_pathz
No folder z matched in the search path : )rg   detailsr   )template_namez,Could not find a template named %(template)sr   )vm_guest_idtemplate_guest_idz:Could not create vm from template with different guest_idsr  r  T)r   r   r   Fr    r   rj  re  rs  r+   rh  r   r  ri  c              3   $   K   | ]  }|d u 
 y wr   rP   r  r5   s     r%   r  z*PyVmomiHelper.deploy_vm.<locals>.<genexpr>       Lq}L   r  r  r  convertr  r  thickr  linked_clonesnapshot_srcz[Parameter 'linked_src' and 'snapshot_src' are required together for linked clone operation.is_template)r   locationzCNo snapshots present for virtual machine or template [%(template)s])	snapshotssnapnamer9   zQvirtual machine "%(template)s" does not contain snapshot named "%(snapshot_src)s"r   Cloner+   )r  r+   r  z Failed to clone virtual machine z to folder z due to permission issue: [])logDirectorysnapshotDirectorysuspendDirectory
vmPathNameCreateVM_Task)r   poolrE   zJFailed to create virtual machine due to invalid configuration parameter %szKFailed to create virtual machine due to product versioning restrictions: %sz@TypeError was returned, please ensure to give correct inputs. %srn   )rj   rk   rg   	clonespecrW   clone_method
annotationri   r  r   r  r  wait_for_ip_addresswait_for_customizationr{   )re   
powered-on	restartedre   forcewait_for_ip_address_timeoutwait_for_customization_timeoutrb   timeout;Customization failed. For detailed information see warnings)rj   rk   rg   instancerl   )rj   rk   r%  )fr]   r   r  rU   rt   rj  rstripr^   r   r   r   rJ   r   endswithsearchIndexFindByInventoryPathr+   get_vm_or_templaterp   r   r   r  r  r  r  r  rb   
ConfigSpecrW   r   RelocateSpecrX   r   r   r"  r0  r   r  r  r  r   ra  anyrd  rZ  r  rE   r  r   r   rI   r  DiskLocatorFlatVer2BackingInfodiskBackingInfor  r  r  r   diskIdr  r   r  DiskMoveOptionscreateNewChildDiskBackingdiskMoveType	CloneSpecr\   r  snapshot!get_snapshots_by_name_recursivelyrootSnapshotListr;   r  ru   NoPermissionr   rg   rY   FileInfofilesr  r   InvalidRequestRestrictedVersionry   ro  r
   rz   r{   r   rZ   r-   ry  r  ReconfigVM_Taskr  r  r   r   r  rc   )"r$   rK   dcpathfullpathf_objr  
destfolderr   r  r  r  r  network_changesnwr   r  r  r   disk_locatorr  r  r6  r~   r}   esx_hostr   clonespec_jsonconfigspec_jsonkwargsrb   annotation_specr  is_customization_okvm_factss"                                     r%   	deploy_vmzPyVmomiHelper.deploy_vmv  s    kkooh5;;KK!!&h!i {{%%c*'$++5DKkk((-ZZ((7GUaIbc
KK!!&TW[WbWb&b!c/
; s#cMF ;;!!T[[..6
[[##FSL4;;|3L$Lu$TU{{H[[##F+t{{e/C#)4;;|+DdkkRH[[##C(&,dkk,.GUH'-t{{</H$++VH((<<XF = )oo#)++$,	G KK!!X\XcXcem&n*1 " 3 
;;z",,4;;z;R,SF~%%*X[_[f[f*f%g{{:&2v~~7L7L7T7T7`eiepepq{e|  AG  AO  AO  AV  AV  A^  A^  f^#';;z#:)/)>)>)F)F %%*f.5 & 7 F ..0 ;;{# "[[5N $

 3 3DLL3>>BRTb c !%!?!?Vg!?!h

++DLL3==/>ZI*.*?*?*G'Y&&++-')$++-%'"f$?%%V%F&&f&5(((7**&*9&&f&5F+f-F+V,  ++j) 	B &=RZ6%9&*Opp&*O	 Ldkk/&B&I&I&KLLP_cgcncncrcr  tH  dI  dUV,	T	w{{:&;;/)-)9)9);DMM&*3' ;;y)"(--"8"8"?"? D%fcffmm.G.GH+.66+>+>+J+J+LL;>66==;T;T;h;h;jL8#{{95?OS < < L#{{959KKLP < < I#{{95@HT < < E28**L/5>L2 MM..55lCD  &3"#{{~>#{{~tD#/58VV5H5H5X5X5r5r2-- 3c- d  FF,,dkk-6P[_[h[h,i	??.2ooI++.--2wz~  {F  {F  3F-  G#EEPVP_P_PpPpO[  F  ]H8})-- 3WY]YdYd3e- f *2!)=)=I&#'??	 &b!<<zF@SZc<dD (,$ (,{{6':$(+TJNIMCFCWZ]C] )8 )_%  ;;/#//1H.h%334??Q^em3nD (,$**40I 99??g%
 ,I6N,T__=O.. +- ,F M !!B{{<("%&&"3"3"5-0\1J-K*))/: ..t4	99??g-'+':':dS\dpqq{{./!$!2!2!4000W)).9 ..t4	99??g-'+':':dS\dwxx{{>*++2+6{{01T[[AY5Z^b^i^ijq^r  w_  __"4<<[N;;45"4<<T[[A^5_`;;78*.*E*EUYU`U`  bB  VC*E  +D'.#'#4#4R#8+/+>+>$'d,4O M M ((,H#22eQYZZm yy-- bKK))OS{{[aObOYOXYZY^Y^O_/a) b bb* {{11 QKK)) /=?H?O/P) Q Qyy22 hKK)) /TV_`a`e`eVf/g) h hh
  	wKK!!&hkrstku&u!vv	ws   +B1x2 J?x2 !t >Bx2  u= x2 u:*Au5/x2 5u::x2 =x/2wx2  x/22x*$x2 *x//x2 2	y.;(y))y.c                     g }|D ]B  }|j                   |k(  r|j                  |       $|| j                  |j                  |      z   }D |S r   )r+   r   r7  childSnapshotList)r$   r  r  snap_objr6  s        r%   r7  z/PyVmomiHelper.get_snapshots_by_name_recursively~  sU    ! 	sH}}()#d&L&LXMgMgiq&rr		s
 r'   c                 h   t         j                  j                         | _        g | j                  _        t         j                  j                         | _        g | j                  _        | j                  | j                         | j                  | j                         | j                  | j                        }||S | j                  | j                         | j                  | j                         | j                  | j                         | j                  | j                         | j                  | j                         | j!                  | j                  | j                         | j#                  | j                         | j%                  | j                         | j'                  | j                         | j(                  d   r^| j                  j*                  j,                  | j(                  d   k7  r.t/        | j(                  d         | j                  _        d| _        | j(                  d   r| j3                         | j                  _        | j                  j4                  | j                  j6                  k7  rt/        | j                  j4                        | j8                  d<   | j:                  j<                  rd| _        na| j                  jA                  | j                        }| jC                  |      }|jD                  jF                  dk(  r| j>                  d|d	d
S | j0                  rt/        | j                        | j8                  d<   | j:                  j<                  rd| _        ndd }	 | j                  jI                  | j                        }| jC                  |      }|jD                  jF                  dk(  r| j>                  d|dd
S | j(                  d   r| j(                  d   r| j(                  d   | j                  j*                  jT                  k7  r| j(                  d   | j8                  d<   | j:                  j<                  rd| _        nc| j                  jW                  | j(                  d         }| jC                  |      }|jD                  jF                  dk(  r| j>                  d|dd
S | j(                  d   rh| j                  j*                  jX                  sH	 | j:                  j<                  s| j                  j[                          d| _        d| j8                  d<   n| j(                  d   s| j                  j*                  jX                  r| j3                         }ta        |      }| j(                  jc                  dd       r"| je                         }|jg                  |       	 | j:                  j<                  s | j                  jh                  d&i | d| _        d| j8                  d<   | j(                  d   d    r| j                  j*                  jX                  r| j:                  jO                  d!       | j                  jt                  jv                  t         jx                  jz                  k7  r2| j:                  j<                  s| j:                  jO                  d"       d| j8                  d<   | j:                  j<                  rd| _        n| j}                         }|d#   r|S | j                  | j                        }| j>                  d$|| j8                  d%S # t         jJ                  jL                  $ r=}| j:                  jO                  dtQ        |jR                        z         Y d }~d }~ww xY w# t\        jJ                  j^                  $ rD}| j:                  jO                  d| j(                  d   d|jR                         Y d }~d }~ww xY w# t         jJ                  jj                  $ r=}| j:                  jO                  dtQ        |jR                        z         Y d }~Kd }~wt         jJ                  jl                  $ r=}	| j:                  jO                  dtQ        |	jR                        z         Y d }	~	d }	~	wt         jJ                  jn                  $ r=}
| j:                  jO                  dtQ        |
jR                        z         Y d }
~
d }
~
wt\        jJ                  jp                  $ r=}| j:                  jO                  dtQ        |jR                        z         Y d }~Sd }~wtr        $ r3}| j:                  jO                  dtQ        |      z         Y d }~d }~ww xY w)'Nr  r  r  Tr  resourcePool)r  rn   relocateri   rW   zPFailed to reconfigure virtual machine due to product versioning restrictions: %srf   reconfigr  r+   renamer	  MarkAsTemplatez Failed to mark virtual machine [z] as template: )r  r  )rE   MarkAsVirtualMachinez.Virtual machine is not marked as template : %szaConverting template to virtual machine operation cannot be performed on the target datastores: %szfFailed to convert template to virtual machine as operation unable access virtual machine component: %sz9Failed to convert template to virtual machine due to : %szGFailed to convert template to virtual machine due to generic error : %sr  existing_vmz3VM is template, not support guest OS customization.z?VM is not in poweroff state, can not do guest OS customization.rk   F)rj   rk   r%  changesrP   )@r   rb   r+  rW   r   r,  rX   r   current_vm_objr   r"  r0  r  r  r   ra  r  r  r   r  r]   r   r  ry  rY   r  r  rR  r[   rU   r   rZ   RelocateVM_Taskry   rz   r{   r>  ru   r=  rt   r   rg   r+   Rename_Taskr   rV  r   NotSupportedr  r   r  updaterW  InvalidStateInvalidDatastoreCannotAccessVmComponentInvalidArgumentr  rq   rr   r   r   customize_exist_vmrc   )r$   errr~   r   r}   r  rI  host_system_objinvalid_state
invalid_dscannot_accessinvalid_argumentgeneric_exc
cus_resultrL  s                  r%   reconfigure_vmzPyVmomiHelper.reconfigure_vm  s   &&++-')$++-%'"d&9&9:%%T-@-@%A,,D4G4G,H?J((0C0C(DD$7$78d&9&9:D$7$78T%8%89((0C0CQUQ`Q`(a##4+>+>#?**$2E2E*F&&d.A.A&B;;|$)<)<)C)C)N)NRVR]R]^jRk)k),T[[-F)GDOO&#'D ;;'!%!7!7!9DMM}}!!T%8%8%E%EE7:4==;M;M7N$$^4;;))*.D'..>>DMM>RD $ 2 24 8Iyy'1+/+>+>$W`hrss 14T__1ED  .{{%%&*#i..>>DOO>TD !..t4	99??g-'+':':dS\dnoo ;;v4;;v#64;;v;NRVReReRlRlRqRq;q+/;;v+>D  ({{%%&*#**66t{{67JK ..t4	99??g-'+':':dS\dlmm ;;}%d.A.A.H.H.Q.Q\{{--''668&*#9=$$%56 ]+0C0C0J0J0S0S 224M}-F{{5"&"2"2"4?3a{{--<D''<<FvF&*#?C$$%;<( ;;'6""))22%%*_%`""**559U9U9`9``imititii%%*k%l 59D  1{{%%&*#!446
h'%%$$T%8%89..%Xbfbvbvww_ yy22 iKK)) /UW`abafafWg/h) i ii2 ;;++ \%%?C{{6?RTUTYTY+[% \ \\$ 99)) ^%% +>@I-J[J[@\+]% ^ ^99-- `%% +CENz~~E^+_% ` ` 9944 [%% +;=F}GXGX=Y+Z% [ [ ;;.. \%% +9;DEUEYEY;Z+[% \ \ a%% +GIRS^I_+`% a aasz   
&] A^1 A` ^.12^))^.1`9``f122a** f1
2c f1"2d f1:2e22f1>(f,,f1c                    d }d}| j                   d   D ]  }|D ]
  }|dvsd}   t        d | j                   d   j                         D              s|s| j                   j                  d      r| j	                  | j
                         	 | j
                  j                  | j                        }| j#                  |      }|j$                  j&                  dk(  r| j(                  d|ddS | j                   d   r`t+        | j,                  | j
                  dd       | j/                  | j
                  | j                   d         }|s| j(                  ddddS | j(                  ddS # t        j                  j                  $ r=}| j                  j                  d	t        |j                        z  
       Y d }~d }~wt        j                  j                  $ r=}| j                  j                  dt        |j                        z  
       Y d }~fd }~wt         $ r=}| j                  j                  dt        |j                        z  
       Y d }~d }~ww xY w)NFr    r   Tc              3   $   K   | ]  }|d u 
 y wr   rP   r  s     r%   r  z3PyVmomiHelper.customize_exist_vm.<locals>.<genexpr>  r  r  r  r  r  zEFailed to customization virtual machine due to CustomizationFault: %srf   z?failed to customization virtual machine due to RuntimeFault: %sz8failed to customization virtual machine due to fault: %srn   customize_existri   r  re   r  r!  r"  r$  wait_for_customize_existrm   )r]   r-  rd  r   rZ  rZ  CustomizeVM_Taskr\   r   ru   CustomizationFaultrU   rt   r   rg   rw   r  ry   rz   r{   rZ   r   r   r  )r$   r~   rC  rD  r   r}   r   rK  s           r%   rc  z PyVmomiHelper.customize_exist_vm  sJ   ++j) 	B pp&*O		 Ldkk/&B&I&I&KLLP_cgcncncrcr  tH  dIT%8%89	u&&77HD &&t,	99??g%#22d9\mnn;;/0t||T-@-@+UZ["&"="=ATAT^b^i^i  kK  _L"=  #M&#'#6#6$\8: :  ..%@@% yy++ 	BKK!!&mpyz{zz  qA  'A!  B  Byy%% 	|KK!!&gjstutytyjz&z!{{ 	uKK!!&`clmnmrmrcs&s!tt	us0   %E- -I#
2G I#"2HI#&2II#c                 d   d}|j                   j                  dvr.t        j                  |       |j                   j                  dvr.|j                   j                  dk(  r|j                   j                  j
                  }t        |j                   j                  d      rb|j                   j                  j                  D ].  }t        |d      s|j                  s||j                  dz   z  }0 |j                  d      }| j                  xs |j                   j                  dk(  | _
        |S )a  
        Wait for a VMware task to complete.  Terminal states are 'error' and 'success'.

        Inputs:
          - task: the task to wait for
          - poll_interval: polling interval to check the task, in seconds

        Modifies:
          - self.change_applied
        r  )rn   successrn   faultMessagemessage;rt  )rz   r{   timesleeprn   rg   r2   ru  rv  r&  rZ   )r$   r~   poll_intervalr   ru   s        r%   ry   zPyVmomiHelper.wait_for_task)  s     	iioo%99JJ}% iioo%99 99??g%		++Ityy7!YY__99 9Eui0U]]!U]]S%88	9 &,,S1	"11QTYY__	5Qr'   c                     t         j                  j                  j                  |d      }t         j                  j                  ||      }| j                  j
                  }|j                  |      S )Nr$   )r  	recursion)r  eventTypeId)r   eventEventFilterSpecByEntityr   eventManager
QueryEvent)r$   rb   eventTypeIdListbyEntity
filterSpecr  s         r%   get_vm_eventszPyVmomiHelper.get_vm_eventsE  sZ    99,,55R65RYY..hO.\
||00&&z22r'   c                    t        ||z        }d}||k  r| j                  |dg      }t        |      rd}||k  r| j                  |ddg      }t        |      ret        |d   t        j
                  j                        s=| j                  j                  d|d   j                  d|d   j                  d       yy	t        j                  |       |d
z  }||k  rt              dk(  r6| j                  j                  d       yt        j                  |       |d
z  }||k  rt              r| j                  j                  d       y| j                  j                  d       y)Nr   CustomizationStartedEventCustomizationSucceededCustomizationFailedz!Customization failed with error {z}:{}FTr9   z1Waiting for customization result event timed out.z0Waiting for customization start event timed out.)r   r  r;   rI   r   r~  r  rU   r  	_wsdlNamefullFormattedMessagerx  ry  )r$   rb   r#  ry  pollthispolleventStartedeventsFinishedResults           r%   r  z$PyVmomiHelper.wait_for_customizationK  s`   7e#$$--b3N2OPL< $&+/+=+=bC[]rBs+t(/0)*>q*A399CcCcd KK,,0DQ0G0Q0QSghiSjSS.A B#(#'

5) A $& +,1KK$$%XY 

5!A+ $, |KKPQ  KKOPr'   )F)NNr   )NNN)r9   )  
   )3rL   rM   rN   r&   rc   r   r   r   r   r   r   r   r"  r0  r3  r   r   r   r;  r>  ra  rf  r  r  r  r  r  r  rZ  r_  rx  r}  r  r  r  r  r  r  r  r  r  r  r  rM  r7  rl  rc  ry   r  r  __classcell__)r_   s   @r%   rR   rR     s!   	S1E.>O(bb(H2h.JDXWGrD(OWXZPKIZ
_B^,@_(B,@,8)B,_\:*X!F7Crd,L$I)V$B!FF[P~x@ AD83r'   rR   c                     t               }  | j                  di dt        ddg d      dt        ddg      d	t        d
d      dt        ddg      dt        dg d      dt        dg d      dt        d      dt        dddgd      dt        d      dt        d
d      dt        d      dt        d      dt        dg dt        t        d
      t        dg d !      t        dg d"!      t        d      t        dg d#!      t        d      t        d      t        d      t        d      t        d      t        d      t        dg d$!      t        d      %      &      d't        di t        t        ddd(g!      t        d      t        dd)      *      +      d,t        dg dt        t        dg d-d.      t        d      t        dd/d0gd/      t        d      t        d      t        ddd(gd      1      &      d2t        di t        di d3t        dd4d5g!      d6t        d      d7t        d      d8t        d
      d9t        d
      d:t        d
      d;t        d
      d<t        d      d=t        d      d>t        dg d?!      d@t        dg d?!      dAt        d      dBt        d      dCt        ddDg      dEt        d      dFt        d
      dGt        d
      dHt        d      dIt        d      dJt        dg dK!      dLt        d
      dMt        d      dNt        d
      dOt        d
      +      dPt        di t        t        dg dQ!      t        dg dQ!      R      +      dSt        d
d      dTt        ddU      dVt        d      dWt        d      dXt        d
d      dYt        ddZ      d[t        dd\      d]t        d      d^t        d
d      d_t        dg d      d`t        d      dat        di t        di dbt        d
      dct        d      ddt        dde      dft        dde      dgt        d      dht        d      dit        ddjk      dlt        d      dmt        d
      dnt        d      dot        d      dpt        d
      dqt        d      drt        d      dst        d      dtt        ddjk      dut        d      dvt        dde      dwt        d      dxt        d      +      dyt        dd       dzt        d
d      d{t        dd|      d}t        dg d      d~t        d      dt        dg d!      dt        d
d       t        | djdWdVggddgg      }ddd}t	        |      }|j
                  d2   dN   r|j
                  d2   dG   s|j                  j                  d       |j
                  d2   dL   s|j                  j                  d       |j
                  d2   dO   s|j                  j                  d       |j                         }|r|j
                  d   d(k(  r|j                  r]|j                  |j                  dj|j                  j                  j                  j                         d        |j                  di | |j
                  dS   r%t!        |j"                  |d|j
                  dS          |j%                  ||j
                  d         }n-|j
                  d   dk(  r|j'                         }n	|j
                  d   dv r~|j                  r|j                  j                  j                  j                         }d}|dk(  r|j
                  d   dvs-|dk(  r|j
                  d   dvs|dk(  r|j
                  d   dk7  rdj}|j                  |j                  ||d        |j                  di | t!        |j"                  ||j
                  d   |j
                  dS   |j
                  d[         }|d   rbdj|d<   |j
                  d   dv rL|j
                  dX   r=t)        |j"                  ||j
                  dY         }|s|j                  d       ||d<   |d   sd|d<   |d   |d<   |d   rdj|d<   |d   |d<   nyt+               |j
                  d   dv r^|j                  r%|j                  djd        |j                  di | |j-                         }|d   r|j                  d|d   z         |d   r |j                  di | y  |j                  di | y )Nr{   ry  r   )r   
poweredoffpowered-offre   r  r   rebootguestreboot-guestr  shutdownguestshutdown-guest	suspended)r   defaultchoicesr   template_src)r   aliasesr	  r  F)r   r  r  notesr  rt  r  )r   r  elementsr  r+   )r   
name_matchfirstlast)r   r  r  r  use_instance_uuidr  r   r  r   )r   r9   r   rd  )r   r  )buslogiclsilogicr  lsilogicsasr   nvme)r  independent_persistentindependent_nonpersistent)r  r  r  )r  r   r   r  r  rz  rb  size_gbsize_kbrE  size_tbr   r   )r   r  r  optionsr@  r   ri  )r{   rA  rE  )r   r  r  r   )noneclientr   r  r   r   )r   r   r   r   r   r{   r   r   biosefir   r   r   r   r   r   r   r   r   )lownormalhighr   r   r   r   r   memory_reservationr   r   r  r   r   r  )r  r  r  r  r  r  r	  r  r$  )r'  r)  r+  )r%  r&  r  rK   zha-datacenterr  rA   r  r   i,  state_change_timeoutr   r  r  r    r  r  r  r	  r  )r   r  r  r  r  r  T)r   no_logr  rX  r  r  r  r  r  r  r  r  r  r  r
  r  r  r!  r  r  r  r  )r  r  r  r|   )argument_specsupports_check_modemutually_exclusiverequired_one_of)rk   rj   zXVirtualization based security requires nested virtualization. Please enable nested_virt.rf   zUVirtualization based security requires (U)EFI secure boot. Please enable secure_boot.zDVirtualization based security requires I/O MMU. Please enable iommu.r   )vm_namerj   current_powerstatedesired_operationr  )
re   r  r  r  r  r  r  r  r  r  re   )re   r  )r  r  r  r  r  r   rj   )re   r  r  r  r  z Waiting for IP address timed outr%  rk   rg   )re   r  r  r  r   r  r  rM  )rj   r  z'Failed to create a virtual machine : %srP   )r   r^  r  r   rR   r]   rU   rt   get_vmr   r+   rp   rq   rr   rs   r  r   r   r   rl  r   r  rM  )	r  rU   r-   pyvrb   r  powerstate_will_change
tmp_resultwait_results	            r%   mainr  k  s   &(MM JyLMJ 5>*:;J fe4J UWI6J vrFCJ FBHJ uJ UWf,=wOJ uJ FE:J J  5!!J" %)v%6"&E<"H $%9  !AE*E3xy5)u%%(%(%(%(u.ST e,	
#JJ 	8/DE&%6
KJ\ u.GQYZ5) $%%RW X"&E"2 e,	8/DiX	
]Jv  "GE* !%% 0  V,	
 #/ #/ "v. !%% 0 E* "&5:]!^ "&5:]!^  U+  U+ !%%:N9O P E*  )-&(9!" !f-#$ *.5)9%& 5)'( u.de)* !f-+, %(-. %)f$5/0 '1wJp "&E;d"e!u6_`qJ~ .J@ UO<AJB &CJD % EJF !fe<GJH %)eS$AIJJ "ua8KJL u%MJN vu5OJP 62?QJR &SJT  F+#/ !fu=  Ve<	
 ' !e, %)eD$A E* !f- 5) 5)  V,  U+ #. %(  56!" E*#$ &59%& !e,'( 5))UJF  UD9GJH  $?IJJ (,'EKJL &"vFMJN E"OJP %)NOQJR #>SJX /3 )?;/ !'/,F %0F

C zz*34zz*%m4JJ  %   Azz*%m4JJ  %| }zz*%g.JJ  %k l 
B 
==!X-  GG ')zz'9'9'D'D'J'J'L&1	   !  *6*}}W%"3;;L&--PWBXY]]2v}}5L'MNF]]7#y0'')F]]7# (G G   %'ZZ%7%7%B%B%H%H%J").&';66==;QYt;t.,>6==QXCY#cDd.+=&--PWBX\gBg-1*GG2'9&:	   !  *6*+CKKV]]7=SU[UbUbcjUkmsmzmz  |R  nS  TJ)$$(y!==)-tty  zG  zG  H]  z^"0b&--PmBn"oK&((-O(P-8Jz*h'#(x !+J!7F:(##'x  *5 1u !"" ==! &K K   &1   !  *6*]]_Fh  %NQWX]Q^%^ _h"6""6"r'   __main__)-
__future__r   r   r   r   __metaclass__DOCUMENTATIONEXAMPLESRETURNrG  rx  r  pyVmomir   r   ImportErroransible.module_utils.basicr   #ansible.module_utils.common.networkr	   ansible.module_utils._textr
   r   @ansible_collections.community.vmware.plugins.module_utils.vmwarer   r   r   r   r   r   r   r   r   r   r   Hansible_collections.community.vmware.plugins.module_utils._argument_specr   Jansible_collections.community.vmware.plugins.module_utils.vm_device_helperr   Eansible_collections.community.vmware.plugins.module_utils.vmware_spbmr   r   rR   r  rL   rP   r'   r%   <module>r     s    A @^@Yv
 
  	" 5 6 9    h j VO7 Odi"G i"XEs#l zF YP  		s   B BB