Example #1
0
def create_vm(vm_folder, resource_pool, datastore, net_name, vm_name, CPU, RAM,
              disk, provision):
    """
        Create a VM with following configurations: CPU, memory, disk
        RAM and attached network/switch
    """
    new_datastore = '[' + datastore.name + '] ' + vm_name  # This creates a new directory with the same naming scheme as the new VM
    vm_config = vim.vm.ConfigSpec()
    """ 
        Create a custom nic specification...
        behold!... this is just a cluster of methods
        going back and forth...
        Exactly how this looks behind the scenes is explained
        in the report
    """
    device_config = []
    # Create NIC
    nic_type = vim.vm.device.VirtualE1000()
    nic_edit = vim.vm.device.VirtualDeviceSpec(
    )  # Create a "template" for a new NIC
    nic_edit.operation = vim.vm.device.VirtualDeviceSpec.Operation.add  # tell the API that we want to create a new device
    nic_edit.device = nic_type  # create a device specikation with the nic_edit name
    nic_edit.device.deviceInfo = vim.Description(
    )  # Initialize methods to set info for the NIC
    nic_edit.device.backing = vim.vm.device.VirtualEthernetCard.NetworkBackingInfo(
    )  # Add backing information to the device specification
    nic_edit.device.backing.network = net_name  # Associate an existing network with the device description
    nic_edit.device.backing.deviceName = net_name.name  # set the device name to the physical or logical network the nic is connected to.
    device_config.append(nic_edit)

    # addd iscsi controller to machine
    scsi_type = vim.vm.device.VirtualLsiLogicController()
    scsi_ctl = vim.vm.device.VirtualDeviceSpec()
    scsi_ctl.operation = vim.vm.device.VirtualDeviceSpec.Operation.add
    scsi_ctl.device = scsi_type
    scsi_ctl.device.deviceInfo = vim.Description()
    scsi_ctl.device.slotInfo = vim.vm.device.VirtualDevice.PciBusSlotInfo()
    scsi_ctl.device.slotInfo.pciSlotNumber = 16
    scsi_ctl.device.key = 22  # random number
    scsi_ctl.device.sharedBus = vim.vm.device.VirtualSCSIController.sharedBus = 'noSharing'
    scsi_ctl.device.busNumber = 0
    scsi_ctl.device.device = 0
    scsi_ctl.device.scsiCtlrUnitNumber = 7
    device_config.append(scsi_ctl)

    vm_config.numCPUs = CPU
    vm_config.name = vm_name
    vm_config.memoryMB = RAM
    vm_config.guestId = 'ubuntu64Guest'
    vm_config.deviceChange = device_config  # Set custom hardware specications from the newly created NIC and vHDD

    vm_files = vim.vm.FileInfo()
    vm_files.vmPathName = new_datastore
    vm_config.files = vm_files

    print('\nCreating VM without disk...')
    vm_folder.CreateVM_Task(config=vm_config, pool=resource_pool)
    add_disk_to_vm(vm_folder, vm_name, disk, provision, datastore)
    return True
Example #2
0
    def _new_nic_spec(self, vm_obj, nic_obj=None, network_params=None):
        network = self._get_network_object(vm_obj, network_params)

        if network_params:
            connected = network_params['connected']
            device_type = network_params['device_type'].lower()
            directpath_io = network_params['directpath_io']
            guest_control = network_params['guest_control']
            label = network_params['label']
            mac_address = network_params['mac_address']
            start_connected = network_params['start_connected']
            wake_onlan = network_params['wake_onlan']
        else:
            connected = self.params['connected']
            device_type = self.params['device_type'].lower()
            directpath_io = self.params['directpath_io']
            guest_control = self.params['guest_control']
            label = self.params['label']
            mac_address = self.params['mac_address']
            start_connected = self.params['start_connected']
            wake_onlan = self.params['wake_onlan']

        if not nic_obj:
            device_obj = self.nic_device_type[device_type]
            nic_spec = vim.vm.device.VirtualDeviceSpec(device=device_obj())
            if mac_address:
                nic_spec.device.addressType = 'manual'
                nic_spec.device.macAddress = mac_address

            if label:
                nic_spec.device.deviceInfo = vim.Description(label=label)
        else:
            nic_spec = vim.vm.device.VirtualDeviceSpec(
                operation=vim.vm.device.VirtualDeviceSpec.Operation.edit,
                device=nic_obj)
            if label and label != nic_obj.deviceInfo.label:
                nic_spec.device.deviceInfo = vim.Description(label=label)
            if mac_address and mac_address != nic_obj.macAddress:
                nic_spec.device.addressType = 'manual'
                nic_spec.device.macAddress = mac_address

        nic_spec.device.backing = self._nic_backing_from_obj(network)
        nic_spec.device.connectable = vim.vm.device.VirtualDevice.ConnectInfo(
            startConnected=start_connected,
            allowGuestControl=guest_control,
            connected=connected)
        nic_spec.device.wakeOnLanEnabled = wake_onlan

        if directpath_io and not isinstance(nic_spec.device,
                                            vim.vm.device.VirtualVmxnet3):
            self.module.fail_json(
                msg=
                'directpath_io can only be used with the vmxnet3 device type')

        if directpath_io and isinstance(nic_spec.device,
                                        vim.vm.device.VirtualVmxnet3):
            nic_spec.device.uptCompatibilityEnabled = True
        return nic_spec
def create_vm(name, si, vm_folder, resource_pool, datastore, network):
    vm_name = name
    datastore_path = "[" + datastore + "]/" + vm_name + "/" + vm_name + ".vmx"
    vmx_file = vim.vm.FileInfo(logDirectory=None,
                               snapshotDirectory=None,
                               suspendDirectory=None,
                               vmPathName=datastore_path)
    configspec = vim.vm.ConfigSpec(name=vm_name,
                                   memoryMB=int(guest['ramsize']),
                                   numCPUs=int(guest['vcpus']),
                                   guestId=guest['guestID'],
                                   version=guest['version'],
                                   files=vmx_file,
                                   cpuHotAddEnabled=True,
                                   memoryHotAddEnabled=True)
    ##添加虚拟设备nic
    nic_spec = vim.vm.device.VirtualDeviceSpec()
    nic_spec.operation = vim.vm.device.VirtualDeviceSpec.Operation.add
    nic_spec.device = vim.vm.device.VirtualE1000()
    nic_spec.device.deviceInfo = vim.Description()
    nic_spec.device.backing = \
     vim.vm.device.VirtualEthernetCard.NetworkBackingInfo()
    nic_spec.device.backing.useAutoDetect = False
    content = si.RetrieveContent()
    nic_spec.device.backing.network = get_obj(content, [vim.Network], network)
    nic_spec.device.backing.deviceName = network
    nic_spec.device.connectable = vim.vm.device.VirtualDevice.ConnectInfo()
    nic_spec.device.connectable.startConnected = True
    nic_spec.device.connectable.allowGuestControl = True
    nic_spec.device.connectable.connected = False
    nic_spec.device.connectable.status = 'untried'
    nic_spec.device.wakeOnLanEnabled = True
    nic_spec.device.addressType = 'assigned'
    configspec.deviceChange.append(nic_spec)
    print("网卡添加成功")
    ##添加sisc控制器
    scsictl_spec = vim.vm.device.VirtualDeviceSpec()
    scsictl_spec.operation = vim.vm.device.VirtualDeviceSpec.Operation.add
    scsictl_spec.device = vim.vm.device.VirtualLsiLogicController()
    scsictl_spec.device.deviceInfo = vim.Description()
    scsictl_spec.device.slotInfo = vim.vm.device.VirtualDevice.PciBusSlotInfo()
    scsictl_spec.device.slotInfo.pciSlotNumber = 16
    scsictl_spec.device.controllerKey = 100
    scsictl_spec.device.unitNumber = 3
    scsictl_spec.device.busNumber = 0
    scsictl_spec.device.hotAddRemove = True
    scsictl_spec.device.sharedBus = 'noSharing'
    scsictl_spec.device.scsiCtlrUnitNumber = 7
    configspec.deviceChange.append(scsictl_spec)
    print("scsi控制器添加成功")
    print("Creating VM{}...".format(vm_name))
    task = vm_folder.CreateVM_Task(config=configspec, pool=resource_pool)
    tasks.wait_for_tasks(si, [task])
Example #4
0
 def add_nic(self, vm, network_name):
     """
     添加网卡
     :param network_name: esxi上网卡名称
     :return:
     """
     spec = vim.vm.ConfigSpec()
     nic_spec = vim.vm.device.VirtualDeviceSpec()
     nic_spec.operation = vim.vm.device.VirtualDeviceSpec.Operation.add
     nic_spec.device = vim.vm.device.VirtualVmxnet3()
     nic_spec.device.deviceInfo = vim.Description()
     nic_spec.device.backing = vim.vm.device.VirtualEthernetCard.NetworkBackingInfo(
     )
     nic_spec.device.backing.useAutoDetect = False
     nic_spec.device.backing.network = self.get_obj([vim.Network],
                                                    network_name)
     nic_spec.device.backing.deviceName = network_name
     nic_spec.device.connectable = vim.vm.device.VirtualDevice.ConnectInfo()
     nic_spec.device.connectable.startConnected = True
     nic_spec.device.connectable.startConnected = True
     nic_spec.device.connectable.allowGuestControl = True
     nic_spec.device.connectable.connected = True
     nic_spec.device.connectable.status = 'untried'
     nic_spec.device.wakeOnLanEnabled = True
     nic_spec.device.addressType = 'generated'
     spec.deviceChange = [nic_spec]
     task = vm.ReconfigVM_Task(spec=spec)
     tasks.wait_for_tasks(self.si, [task])
Example #5
0
    def run(self, vm_id, network_id, ip, subnet, gateway=None, domain=None):
        # convert ids to stubs
        virtualmachine = inventory.get_virtualmachine(self.service_instance, vm_id)
        network = inventory.get_network(self.service_instance, network_id)

        # add new vnic
        configspec = vim.vm.ConfigSpec()
        nic = vim.vm.device.VirtualDeviceSpec()
        nic.operation = vim.vm.device.VirtualDeviceSpec.Operation.add  # or edit if a device exists
        nic.device = vim.vm.device.VirtualVmxnet3()
        nic.device.wakeOnLanEnabled = True
        nic.device.addressType = 'assigned'
        # docs recommend using unique negative integers as temporary keys.
        # See https://github.com/vmware/pyvmomi/blob/master/docs/vim/vm/device/VirtualDevice.rst
        nic.device.key = -1
        nic.device.deviceInfo = vim.Description()
        nic.device.deviceInfo.label = 'Network Adapter-%s' % (ip)
        nic.device.deviceInfo.summary = 'summary'
        nic.device.backing = vim.vm.device.VirtualEthernetCard.DistributedVirtualPortBackingInfo()
        nic.device.backing.port = vim.dvs.PortConnection()
        nic.device.backing.port.switchUuid = network.config.distributedVirtualSwitch.uuid
        nic.device.backing.port.portgroupKey = network.config.key
        nic.device.connectable = vim.vm.device.VirtualDevice.ConnectInfo()
        nic.device.connectable.startConnected = True
        nic.device.connectable.allowGuestControl = True
        configspec.deviceChange = [nic]
        add_vnic_task = virtualmachine.ReconfigVM_Task(configspec)
        successfully_added_vnic = self._wait_for_task(add_vnic_task)

        # customize VM
        cust_item = vim.CustomizationSpecItem()
        cust_specinfo = vim.CustomizationSpecInfo()
        cust_specinfo.name = 'assignip-' + str(uuid.uuid4())
        cust_specinfo.type = 'Linux'
        cust_item.info = cust_specinfo

        # fixed ip
        cust_spec = vim.vm.customization.Specification()
        cust_item.spec = cust_spec
        ip_adapter_mapping = vim.vm.customization.AdapterMapping()
        ip_adapter_mapping.adapter = vim.vm.customization.IPSettings()
        ip_adapter_mapping.adapter.ip = vim.vm.customization.FixedIp()
        ip_adapter_mapping.adapter.ip.ipAddress = ip
        ip_adapter_mapping.adapter.subnetMask = subnet
        ip_adapter_mapping.adapter.gateway = gateway
        ip_adapter_mapping.adapter.dnsDomain = domain
        cust_spec.nicSettingMap = [ip_adapter_mapping]
        cust_spec.identity = vim.vm.customization.LinuxPrep()
        cust_spec.identity.hostName = vim.vm.customization.PrefixNameGenerator()
        cust_spec.identity.hostName.base = 'st2'
        cust_spec.identity.domain = 'demo.net'
        cust_spec.globalIPSettings = vim.vm.customization.GlobalIPSettings()

        try:
            self.service_instance.customizationSpecManager.CreateCustomizationSpec(cust_item)
        except:
            self.logger.exception('Failed to create customization spec.')
            raise

        return {'state': successfully_added_vnic}
Example #6
0
    def add_nic(self, vm, network):
        '''Function that adds a NIC to the VM and connects it to the portgroup'''

        # Define specifications
        spec = vim.vm.ConfigSpec()
        nic_changes = []
        nic_spec = vim.vm.device.VirtualDeviceSpec()
        nic_spec.operation = vim.vm.device.VirtualDeviceSpec.Operation.add
        nic_spec.device = vim.vm.device.VirtualE1000()
        nic_spec.device.deviceInfo = vim.Description()
        nic_spec.device.deviceInfo.summary = 'vCenter API test'
        nic_spec.device.backing = vim.vm.device.VirtualEthernetCard.NetworkBackingInfo(
        )
        nic_spec.device.backing.useAutoDetect = False
        nic_spec.device.backing.deviceName = network.name
        nic_spec.device.connectable = vim.vm.device.VirtualDevice.ConnectInfo()
        nic_spec.device.connectable.startConnected = True
        nic_spec.device.connectable.allowGuestControl = True
        nic_spec.device.connectable.connected = False
        nic_spec.device.connectable.status = 'untried'
        nic_spec.device.wakeOnLanEnabled = True
        nic_spec.device.addressType = 'assigned'
        nic_changes.append(nic_spec)
        spec.deviceChange = nic_changes

        # Perform creation task
        try:
            print("Attaching VM to portgroup ...")
            task = vm.ReconfigVM_Task(spec=spec)
            WaitForTask(task)
            print("Successfully added VM to portgroup.")
        except Exception as e:
            print(e)
Example #7
0
 def add_floppy(self, vm):
     # 查找设备控制器
     for dev in vm.config.hardware.device:
         if isinstance(dev, vim.vm.device.VirtualIDEController):
             # If there are less than 2 devices attached, we can use it.
             if len(dev.device) < 2:
                 controller = dev
             else:
                 controller = None
     spec = vim.vm.ConfigSpec()
     floppy_spec = vim.vm.device.VirtualDeviceSpec()
     floppy_spec.operation = vim.vm.device.VirtualDeviceSpec.Operation.add
     floppy_spec.device = vim.vm.device.VirtualFloppy()
     floppy_spec.device.deviceInfo = vim.Description()
     floppy_spec.device.backing = vim.vm.device.VirtualFloppy.RemoteDeviceBackingInfo(
     )
     floppy_spec.device.connectable = vim.vm.device.VirtualDevice.ConnectInfo(
     )
     floppy_spec.device.connectable.allowGuestControl = True
     floppy_spec.device.connectable.startConnected = False
     floppy_spec.device.controllerKey = controller.key
     floppy_spec.device.key = 8000
     spec.deviceChange = [floppy_spec]
     task = vm.ReconfigVM_Task(spec=spec)
     tasks.wait_for_tasks(self.si, [task])
Example #8
0
    def _add_new_hard_disk(self, disk_label, size_gb, unit_number, controller_key=1000, thin_provision=True, datastore_path=None, vm_name=None):

        key = random.randint(-2099, -2000)

        size_kb = int(size_gb * 1024.0 * 1024.0)

        disk_spec = vim.vm.device.VirtualDeviceSpec()
        disk_spec.fileOperation = 'create'
        disk_spec.operation = vim.vm.device.VirtualDeviceSpec.Operation.add

        disk_spec.device = vim.vm.device.VirtualDisk()
        disk_spec.device.key = key
        disk_spec.device.deviceInfo = vim.Description()
        disk_spec.device.deviceInfo.label = disk_label
        disk_spec.device.deviceInfo.summary = "{0} GB".format(size_gb)

        disk_spec.device.backing = vim.vm.device.VirtualDisk.FlatVer2BackingInfo()
        disk_spec.device.backing.thinProvisioned = thin_provision
        disk_spec.device.backing.diskMode = 'persistent'

        disk_spec.device.backing.fileName = '{datastore_path}/{disk_label}.vmdk'.format(datastore_path=datastore_path, disk_label=disk_label)

        disk_spec.device.controllerKey = controller_key
        disk_spec.device.unitNumber = unit_number
        disk_spec.device.capacityInKB = size_kb

        return disk_spec
Example #9
0
    def create_controller(self, ctl_type, bus_sharing, bus_number=0):
        """
        Create new disk or USB controller with specified type
        Args:
            ctl_type: controller type
            bus_number: disk controller bus number
            bus_sharing: noSharing, virtualSharing, physicalSharing

        Return: Virtual device spec for virtual controller
        """
        if ctl_type == 'sata' or ctl_type == 'nvme' or ctl_type in self.device_helper.scsi_device_type.keys(
        ):
            disk_ctl = self.device_helper.create_disk_controller(
                ctl_type, bus_number, bus_sharing)
        elif ctl_type in self.device_helper.usb_device_type.keys():
            disk_ctl = vim.vm.device.VirtualDeviceSpec()
            disk_ctl.operation = vim.vm.device.VirtualDeviceSpec.Operation.add
            disk_ctl.device = self.device_helper.usb_device_type.get(
                ctl_type)()

            if ctl_type == 'usb2':
                disk_ctl.device.key = 7000
            elif ctl_type == 'usb3':
                disk_ctl.device.key = 14000

            disk_ctl.device.deviceInfo = vim.Description()
            disk_ctl.device.busNumber = bus_number

        return disk_ctl
Example #10
0
def esxi_add_new_nic_process(vm, si, network_name):
    nic_prefix_label = 'Network adapter '
    nic_count = 0
    for dev in vm.config.hardware.device:
        if dev.deviceInfo.label.find(nic_prefix_label) >= 0:
            nic_count = nic_count + 1
    nic_label = nic_prefix_label + str(nic_count + 1)

    nic_spec = vim.vm.device.VirtualDeviceSpec()
    nic_spec.operation = vim.vm.device.VirtualDeviceSpec.Operation.add
    nic_spec.device = vim.vm.device.VirtualE1000()
    nic_spec.device.wakeOnLanEnabled = True
    nic_spec.device.addressType = 'generated'
    nic_spec.device.key = 4000
    nic_spec.device.deviceInfo = vim.Description()
    nic_spec.device.deviceInfo.label = nic_label

    nic_spec.device.backing = vim.vm.device.VirtualEthernetCard.NetworkBackingInfo(
    )
    nic_spec.device.backing.network = get_obj(si.content, [vim.Network],
                                              network_name)
    nic_spec.device.backing.deviceName = network_name

    nic_spec.device.connectable = vim.vm.device.VirtualDevice.ConnectInfo()
    nic_spec.device.connectable.startConnected = True
    nic_spec.device.connectable.connected = True
    nic_spec.device.connectable.allowGuestControl = True

    dev_changes = []
    dev_changes.append(nic_spec)
    spec = vim.vm.ConfigSpec()
    spec.deviceChange = dev_changes
    task = vm.ReconfigVM_Task(spec=spec)
    tasks.wait_for_tasks(si, [task])
    def create_controller(self, ctl_type, bus_number=0):
        """
        Create new disk or USB controller with specified type
        Args:
            ctl_type: controller type
            bus_number: disk controller bus number

        Return: Virtual device spec for virtual controller
        """
        disk_ctl = vim.vm.device.VirtualDeviceSpec()
        disk_ctl.operation = vim.vm.device.VirtualDeviceSpec.Operation.add
        if ctl_type == 'sata':
            disk_ctl.device = self.sata_device_type()
            disk_ctl.device.key = -randint(15000, 19999)
        elif ctl_type == 'nvme':
            disk_ctl.device = self.nvme_device_type()
            disk_ctl.device.key = -randint(31000, 39999)
        elif ctl_type in self.scsi_device_type.keys():
            disk_ctl.device = self.scsi_device_type.get(ctl_type)()
            disk_ctl.device.key = -randint(1000, 6999)
            disk_ctl.device.hotAddRemove = True
            disk_ctl.device.sharedBus = 'noSharing'
            disk_ctl.device.scsiCtlrUnitNumber = 7
        elif ctl_type in self.usb_device_type.keys():
            disk_ctl.device = self.usb_device_type.get(ctl_type)()
            if ctl_type == 'usb2':
                disk_ctl.device.key = 7000
            elif ctl_type == 'usb3':
                disk_ctl.device.key = 14000

        disk_ctl.device.deviceInfo = vim.Description()
        disk_ctl.device.busNumber = bus_number

        return disk_ctl
    def create_tpm(self):
        vtpm_device_spec = vim.vm.device.VirtualDeviceSpec()
        vtpm_device_spec.operation = vim.vm.device.VirtualDeviceSpec.Operation.add
        vtpm_device_spec.device = vim.vm.device.VirtualTPM()
        vtpm_device_spec.device.deviceInfo = vim.Description()

        return vtpm_device_spec
    def create_scsi_controller(self,
                               scsi_type,
                               bus_number,
                               bus_sharing='noSharing'):
        """
        Create SCSI Controller with given SCSI Type and SCSI Bus Number
        Args:
            scsi_type: Type of SCSI
            bus_number: SCSI Bus number to be assigned
            bus_sharing: noSharing, virtualSharing, physicalSharing

        Returns: Virtual device spec for SCSI Controller

        """
        scsi_ctl = vim.vm.device.VirtualDeviceSpec()
        scsi_ctl.operation = vim.vm.device.VirtualDeviceSpec.Operation.add
        scsi_device = self.scsi_device_type.get(
            scsi_type, vim.vm.device.ParaVirtualSCSIController)
        scsi_ctl.device = scsi_device()
        scsi_ctl.device.deviceInfo = vim.Description()
        scsi_ctl.device.busNumber = bus_number
        # While creating a new SCSI controller, temporary key value
        # should be unique negative integers
        scsi_ctl.device.key = -randint(1000, 9999)
        scsi_ctl.device.hotAddRemove = True
        scsi_ctl.device.sharedBus = bus_sharing
        scsi_ctl.device.scsiCtlrUnitNumber = 7

        return scsi_ctl
Example #14
0
    def vnic_compose_empty(device=None):
        """
        Compose empty vNIC for next attaching to a network
        :param device: <vim.vm.device.VirtualVmxnet3 or None> Device for this this 'spec' will be composed.
            If 'None' a new device will be composed.
            'Operation' - edit/add' depends on if device existed
        :return: <vim.vm.device.VirtualDeviceSpec>
        """
        nicspec = vim.vm.device.VirtualDeviceSpec()

        if device:
            nicspec.device = device
            nicspec.operation = vim.vm.device.VirtualDeviceSpec.Operation.edit
        else:
            nicspec.operation = vim.vm.device.VirtualDeviceSpec.Operation.add
            nicspec.device = vim.vm.device.VirtualVmxnet3()
            nicspec.device.wakeOnLanEnabled = True
            nicspec.device.deviceInfo = vim.Description()

            nicspec.device.connectable = vim.vm.device.VirtualDevice.ConnectInfo(
            )
            nicspec.device.connectable.startConnected = True
            nicspec.device.connectable.allowGuestControl = True

        return nicspec
Example #15
0
def add_nic(content, vm, network, macAddress):
    spec = vim.vm.ConfigSpec()
    nic_changes = []

    nic_spec = vim.vm.device.VirtualDeviceSpec()
    nic_spec.operation = vim.vm.device.VirtualDeviceSpec.Operation.add

    nic_spec.device = vim.vm.device.VirtualE1000()

    nic_spec.device.deviceInfo = vim.Description()
    nic_spec.device.deviceInfo.summary = 'automated'

    nic_spec.device.backing = vim.vm.device.VirtualEthernetCard.NetworkBackingInfo()
    nic_spec.device.backing.useAutoDetect = False
    nic_spec.device.backing.network = GetNet(content, network)
    nic_spec.device.backing.deviceName = network

    nic_spec.device.connectable = vim.vm.device.VirtualDevice.ConnectInfo()
    nic_spec.device.connectable.startConnected = True
    nic_spec.device.connectable.startConnected = True
    nic_spec.device.connectable.allowGuestControl = True
    nic_spec.device.connectable.connected = True
    nic_spec.device.connectable.status = 'untried'
    nic_spec.device.wakeOnLanEnabled = True
    nic_spec.device.addressType = 'manual'
    nic_spec.device.macAddress = macAddress
    nic_changes.append(nic_spec)
    spec.deviceChange = nic_changes
    e = vm.ReconfigVM_Task(spec=spec)
    print "\t\tNIC added to VM"
Example #16
0
def add_nic(si, vm, network):

    spec = vim.vm.ConfigSpec()
    nic_changes = []

    nic_spec = vim.vm.device.VirtualDeviceSpec()
    nic_spec.operation = vim.vm.device.VirtualDeviceSpec.Operation.add

    nic_spec.device = vim.vm.device.VirtualE1000()

    nic_spec.device.deviceInfo = vim.Description()
    nic_spec.device.deviceInfo.summary = 'vCenter API test'

    nic_spec.device.backing = \
        vim.vm.device.VirtualEthernetCard.NetworkBackingInfo()
    nic_spec.device.backing.useAutoDetect = False
    content = si.RetrieveContent()
    nic_spec.device.backing.network = get_obj(content, [vim.Network], network)
    nic_spec.device.backing.deviceName = network

    nic_spec.device.connectable = vim.vm.device.VirtualDevice.ConnectInfo()
    nic_spec.device.connectable.startConnected = True
    nic_spec.device.connectable.startConnected = True
    nic_spec.device.connectable.allowGuestControl = True
    nic_spec.device.connectable.connected = False
    nic_spec.device.connectable.status = 'untried'
    nic_spec.device.wakeOnLanEnabled = True
    nic_spec.device.addressType = 'assigned'

    nic_changes.append(nic_spec)
    spec.deviceChange = nic_changes
    e = vm.ReconfigVM_Task(spec=spec)
    print "NIC CARD ADDED"
def create_nic(content, portGroup):
    nic_spec = vim.vm.device.VirtualDeviceSpec()
    nic_spec.operation = vim.vm.device.VirtualDeviceSpec.Operation.add
    nic_spec.device = vim.vm.device.VirtualE1000e()
    nic_spec.device.wakeOnLanEnabled = True
    nic_spec.device.deviceInfo = vim.Description()
    try:
        network = get_obj(content, [vim.dvs.DistributedVirtualPortgroup],
                          portGroup)
        dvs_port_connection = vim.dvs.PortConnection()
        dvs_port_connection.portgroupKey = network.key
        dvs_port_connection.switchUuid = network.config.distributedVirtualSwitch.uuid
        nic_spec.device.backing = vim.vm.device.VirtualEthernetCard.DistributedVirtualPortBackingInfo(
        )
        nic_spec.device.backing.port = dvs_port_connection
    except:
        nic_spec.device.backing = vim.vm.device.VirtualEthernetCard.NetworkBackingInfo(
        )
        nic_spec.device.backing.network = get_obj(content, [vim.Network],
                                                  portGroup)
        nic_spec.device.backing.deviceName = portGroup
    nic_spec.device.connectable = vim.vm.device.VirtualDevice.ConnectInfo()
    nic_spec.device.connectable.startConnected = True
    nic_spec.device.connectable.allowGuestControl = True
    nic_spec.device.connectable.connected = True
    return nic_spec
Example #18
0
    def get_vm_reconfig_spec(self, network_obj, stay_connected, network_type,
                             wake_on_lan):
        network_spec = vim.vm.device.VirtualDeviceSpec()
        network_spec.operation = vim.vm.device.VirtualDeviceSpec.Operation.add

        if network_type.lower() == 'e1000':
            network_spec.device = vim.vm.device.VirtualE1000()
        elif network_type.lower() == 'flexible':
            network_spec.device = vim.vm.device.VirtualPCNet32()
        elif network_type.lower() == 'vmxnet':
            network_spec.device = vim.vm.device.VirtualVmxnet()
        elif network_type.lower() == 'enhancedvmxnet':
            network_spec.device = vim.vm.device.VirtualVmxnet2()
        elif network_type.lower() == 'vmxnet3':
            network_spec.device = vim.vm.device.VirtualVmxnet3()
        else:
            network_spec.device = vim.vm.device.VirtualEthernetCard()

        network_spec.device.wakeOnLanEnabled = wake_on_lan
        network_spec.device.deviceInfo = vim.Description()
        network_spec.device.backing = \
            vim.vm.device.VirtualEthernetCard.NetworkBackingInfo()
        network_spec.device.backing.network = network_obj
        network_spec.device.backing.deviceName = network_obj.name

        network_spec.device.connectable = \
            vim.vm.device.VirtualDevice.ConnectInfo()
        network_spec.device.connectable.startConnected = stay_connected
        network_spec.device.connectable.allowGuestControl = True

        # creating reconfig spec
        vm_reconfig_spec = vim.vm.ConfigSpec()
        vm_reconfig_spec.deviceChange = [network_spec]
        return vm_reconfig_spec
Example #19
0
 def nic_info(self,
              nic_type='Vmxnet3',
              mac_address=None,
              label=None,
              dv_pg_obj=None):
     nic_spec = vim.vm.device.VirtualDeviceSpec()
     nic_spec.operation = vim.vm.device.VirtualDeviceSpec.Operation.add
     if nic_type == 'Vmxnet3':
         nic_spec.device = vim.vm.device.VirtualVmxnet3()
     elif nic_type == 'E1000':
         nic_spec.device = vim.vm.device.VirtualE1000()
     if mac_address:
         nic_spec.device.macAddress = mac_address
     nic_spec.device.deviceInfo = vim.Description()
     nic_spec.device.connectable = vim.vm.device.VirtualDevice.ConnectInfo()
     nic_spec.device.connectable.startConnected = True
     nic_spec.device.connectable.allowGuestControl = True
     nic_spec.device.connectable.connected = True
     nic_spec.device.wakeOnLanEnabled = True
     nic_spec.device.addressType = 'assigned'
     if label:
         nic_spec.device.deviceInfo.label = label
     port = vim.dvs.PortConnection()
     # port.switchUuid = '54 01 36 50 13 35 cf f0-3d ad c9 74 36 95 2f 7e'
     # port.portgroupKey = 'dvportgroup-43'
     if dv_pg_obj:
         port.portgroupKey = dv_pg_obj.key
         port.switchUuid = dv_pg_obj.config.distributedVirtualSwitch.uuid
     nic_spec.device.backing = vim.vm.device.VirtualEthernetCard.DistributedVirtualPortBackingInfo(
     )
     nic_spec.device.backing.port = port
     return nic_spec
Example #20
0
    def vnic_attach_to_network_standard(nicspec, network, logger):
        """
        Attach vNIC to a 'usual' network
        :param nicspec: <vim.vm.device.VirtualDeviceSpec>
        :param network: <vim.Network>
        :param logger:
        :return: updated 'nicspec'
        """
        if nicspec and network_is_standard(network):
            network_name = network.name
            nicspec.device.backing = vim.vm.device.VirtualEthernetCard.NetworkBackingInfo(
            )
            nicspec.device.backing.network = network

            nicspec.device.wakeOnLanEnabled = True
            nicspec.device.deviceInfo = vim.Description()

            nicspec.device.backing.deviceName = network_name

            nicspec.device.connectable = vim.vm.device.VirtualDevice.ConnectInfo(
            )
            nicspec.device.connectable.startConnected = True
            nicspec.device.connectable.allowGuestControl = True

            logger.debug(
                u"Assigning network '{}' for vNIC".format(network_name))
        else:
            # logger.warn(u"Cannot assigning network '{}' for vNIC {}".format(network, nicspec))
            logger.warn(u"Cannot assigning network  for vNIC ".format(
                network, nicspec))
        return nicspec
Example #21
0
    def attach_cdrom_drive(self, name):
        """Attaches cd/dvd drive to the virtual machine."""
        vm = self.get_vm_obj(name, fail_missing=True)
        controller = None
        cdrom_device_key = 3000  # 300x reserved for cd/dvd drives in vmware
        # Find last IDE controller and free device key
        for device in vm.config.hardware.device:
            if isinstance(device, vim.vm.device.VirtualIDEController):
                controller = device
            if isinstance(device, vim.vm.device.VirtualCdrom):
                cdrom_device_key = int(device.key) + 1

        cdspec = vim.vm.device.VirtualDeviceSpec()
        cdspec.operation = vim.vm.device.VirtualDeviceSpec.Operation.add
        cdspec.device = vim.vm.device.VirtualCdrom(deviceInfo=vim.Description(
            label='CD/DVD drive 1', summary='Remote device'))
        cdspec.device.key = cdrom_device_key
        cdspec.device.controllerKey = controller.key

        cdspec.device.backing = vim.vm.device.VirtualCdrom.RemotePassthroughBackingInfo(
            deviceName='', useAutoDetect=False, exclusive=False)

        cdspec.device.connectable = vim.vm.device.VirtualDevice.ConnectInfo(
            startConnected=False,
            allowGuestControl=True,
            connected=False,
            status='untried')

        config_spec = vim.vm.ConfigSpec(deviceChange=[cdspec])
        self.logger.info('Attaching device to the virtual machine...')
        task = vm.ReconfigVM_Task(config_spec)
        self.wait_for_tasks([task])
Example #22
0
    def attach_floppy_drive(self, name):
        """Attaches floppy drive to the virtual machine."""
        vm = self.get_vm_obj(name, fail_missing=True)
        controller = None
        floppy_device_key = 8000  # 800x reserved for floppies
        # Find Super I/O controller and free device key
        for device in vm.config.hardware.device:
            if isinstance(device, vim.vm.device.VirtualSIOController):
                controller = device
            if isinstance(device, vim.vm.device.VirtualFloppy):
                floppy_device_key = int(device.key) + 1

        floppyspec = vim.vm.device.VirtualDeviceSpec()
        floppyspec.operation = vim.vm.device.VirtualDeviceSpec.Operation.add
        floppyspec.device = vim.vm.device.VirtualFloppy(
            deviceInfo=vim.Description(label='Floppy drive 1',
                                       summary='Remote device'))
        floppyspec.device.key = floppy_device_key
        floppyspec.device.controllerKey = controller.key

        floppyspec.device.backing = vim.vm.device.VirtualFloppy.RemoteDeviceBackingInfo(
            deviceName='', useAutoDetect=False)

        floppyspec.device.connectable = vim.vm.device.VirtualDevice.ConnectInfo(
            startConnected=False,
            allowGuestControl=True,
            connected=False,
            status='untried')

        config_spec = vim.vm.ConfigSpec(deviceChange=[floppyspec])
        self.logger.info('Attaching device to the virtual machine...')
        task = vm.ReconfigVM_Task(config_spec)
        self.wait_for_tasks([task])
Example #23
0
def add_nic(vm, mac, port):
    """
    Add NIC to vm
    """
    spec = vim.vm.ConfigSpec()
    nic_changes = []
    nic_spec = vim.vm.device.VirtualDeviceSpec()
    nic_spec.operation = vim.vm.device.VirtualDeviceSpec.Operation.add

    nic_spec.device = vim.vm.device.VirtualE1000()
    nic_spec.device.deviceInfo = vim.Description()
    nic_spec.device.deviceInfo.summary = 'vCenter API'

    nic_spec.device.backing = \
        vim.vm.device.VirtualEthernetCard.DistributedVirtualPortBackingInfo()
    nic_spec.device.backing.port = vim.dvs.PortConnection()
    nic_spec.device.backing.port.portgroupKey = port.portgroupKey
    nic_spec.device.backing.port.switchUuid = port.dvsUuid
    nic_spec.device.backing.port.portKey = port.key

    nic_spec.device.connectable = vim.vm.device.VirtualDevice.ConnectInfo()
    nic_spec.device.connectable.startConnected = True
    nic_spec.device.connectable.allowGuestControl = True
    nic_spec.device.connectable.connected = False
    nic_spec.device.connectable.status = 'untried'

    nic_spec.device.wakeOnLanEnabled = True
    nic_spec.device.addressType = 'assigned'
    nic_spec.device.macAddress = mac

    nic_changes.append(nic_spec)
    spec.deviceChange = nic_changes
    vm.ReconfigVM_Task(spec=spec)
    print("Nic card added success ...")
Example #24
0
    def create_network_adapter(self, device_info):
        nic = vim.vm.device.VirtualDeviceSpec()
        nic.device = self.get_device_type(
            device_type=device_info.get('device_type', 'vmxnet3'))
        nic.device.deviceInfo = vim.Description()
        nic.device.deviceInfo.summary = device_info['name']
        nic.device.backing = vim.vm.device.VirtualEthernetCard.NetworkBackingInfo(
        )
        nic.device.backing.deviceName = device_info['name']
        nic.device.connectable = vim.vm.device.VirtualDevice.ConnectInfo()
        nic.device.connectable.startConnected = device_info.get(
            'start_connected', True)
        nic.device.connectable.allowGuestControl = True
        nic.device.connectable.connected = device_info.get('connected', True)
        if 'manual_mac' in device_info:
            nic.device.addressType = 'manual'
            nic.device.macAddress = device_info['manual_mac']
        else:
            nic.device.addressType = 'generated'
        if 'directpath_io' in device_info:
            if isinstance(nic.device, vim.vm.device.VirtualVmxnet3):
                nic.device.uptCompatibilityEnabled = device_info[
                    'directpath_io']
            else:
                self.module.fail_json(
                    msg='UPT is only compatible for Vmxnet3 adapter.' +
                    ' Clients can set this property enabled or disabled if ethernet virtual device is Vmxnet3.'
                )

        return nic
    def create_nvdimm_controller(self):
        nvdimm_ctl = vim.vm.device.VirtualDeviceSpec()
        nvdimm_ctl.operation = vim.vm.device.VirtualDeviceSpec.Operation.add
        nvdimm_ctl.device = vim.vm.device.VirtualNVDIMMController()
        nvdimm_ctl.device.deviceInfo = vim.Description()
        nvdimm_ctl.device.key = -randint(27000, 27999)

        return nvdimm_ctl
Example #26
0
    def add_network(self, networks):

        networks = json.loads(networks)

        devs = self.vm.config.hardware.device

        # nic_prefix_label = 'Network adapter '

        for network in networks:

            # 获取网络设备信息
            local_network_port_group = network_port_group_manage.get_network_by_id(
                network)

            # 开始添加网卡信息
            spec = vim.vm.ConfigSpec()
            nic_changes = []

            nic_spec = vim.vm.device.VirtualDeviceSpec()
            nic_spec.operation = vim.vm.device.VirtualDeviceSpec.Operation.add
            nic_spec.device = vim.vm.device.VirtualE1000()
            nic_spec.device.deviceInfo = vim.Description()
            nic_spec.device.deviceInfo.summary = 'vCenter API test'

            # content = self.si.RetrieveContent()

            network = get_obj(self.content, [vim.Network],
                              local_network_port_group.name)
            if isinstance(network, vim.OpaqueNetwork):

                nic_spec.device.backing = \
                    vim.vm.device.VirtualEthernetCard.OpaqueNetworkBackingInfo()
                nic_spec.device.backing.opaqueNetworkType = \
                    network.summary.opaqueNetworkType
                nic_spec.device.backing.opaqueNetworkId = \
                    network.summary.opaqueNetworkId
            else:

                nic_spec.device.backing = \
                    vim.vm.device.VirtualEthernetCard.NetworkBackingInfo()
                nic_spec.device.backing.useAutoDetect = False
                nic_spec.device.backing.deviceName = network.name

            nic_spec.device.connectable = vim.vm.device.VirtualDevice.ConnectInfo(
            )
            nic_spec.device.connectable.startConnected = True
            nic_spec.device.connectable.allowGuestControl = True
            nic_spec.device.connectable.connected = False
            nic_spec.device.connectable.status = 'untried'
            nic_spec.device.wakeOnLanEnabled = True
            nic_spec.device.addressType = 'assigned'

            nic_changes.append(nic_spec)
            spec.deviceChange = nic_changes
            task = self.vm.ReconfigVM_Task(spec=spec)
            wait_for_tasks(self.si, [task])
        # 同步云主机网卡信息
        sync_network_device(self.platform_id, self.vm)
Example #27
0
class Hardware:
    device_obj = vim.vm.device.VirtualEthernetCard()  # type: ignore
    device_obj.deviceInfo = vim.Description()  # type: ignore
    device_obj.deviceInfo.label = 'Network adapter 123'
    device_obj.macAddress = 'mac test'
    device_obj.backing = vim.vm.device.VirtualDevice.BackingInfo(
    )  # type: ignore
    device_obj.wakeOnLanEnabled = True
    device = [device_obj]
    def create_nvme_controller(bus_number):
        nvme_ctl = vim.vm.device.VirtualDeviceSpec()
        nvme_ctl.operation = vim.vm.device.VirtualDeviceSpec.Operation.add
        nvme_ctl.device = vim.vm.device.VirtualNVMEController()
        nvme_ctl.device.deviceInfo = vim.Description()
        nvme_ctl.device.key = -randint(31000, 39999)
        nvme_ctl.device.busNumber = bus_number

        return nvme_ctl
    def create_sata_controller(bus_number):
        sata_ctl = vim.vm.device.VirtualDeviceSpec()
        sata_ctl.operation = vim.vm.device.VirtualDeviceSpec.Operation.add
        sata_ctl.device = vim.vm.device.VirtualAHCIController()
        sata_ctl.device.deviceInfo = vim.Description()
        sata_ctl.device.busNumber = bus_number
        sata_ctl.device.key = -randint(15000, 19999)

        return sata_ctl
Example #30
0
def ADD_NIC(content, VM_name, network, si):

    # VM exist ?

    VM = get_obj(content, [vim.VirtualMachine], VM_name)

    if VM is None:
        raise SystemExit(bcolors.FAIL + "Unable to locate VirtualMachine " + VM_name + bcolors.ENDC)

    # NIC exist ?

    exist_networks = GET_NICs(content, VM_name)

    for check_network in exist_networks:
        if check_network == network:
            print (bcolors.WARNING + network + " at " + VM_name + " already exist" + bcolors.ENDC)
            return

    spec = vim.vm.ConfigSpec()
    nic_changes = []
 
    nic_spec = vim.vm.device.VirtualDeviceSpec()
    nic_spec.operation = vim.vm.device.VirtualDeviceSpec.Operation.add
 
    nic_spec.device = vim.vm.device.VirtualVmxnet3()
 
    nic_spec.device.deviceInfo = vim.Description()
    nic_spec.device.deviceInfo.summary = 'vCenter API test'

    nic_spec.device.backing = \
    vim.vm.device.VirtualEthernetCard.NetworkBackingInfo()
    nic_spec.device.backing.useAutoDetect = False
    content = si.RetrieveContent()
    nic_spec.device.backing.network = get_obj(content, [vim.Network], network)
    nic_spec.device.backing.deviceName = network
 
    nic_spec.device.connectable = vim.vm.device.VirtualDevice.ConnectInfo()
    nic_spec.device.connectable.startConnected = True
    nic_spec.device.connectable.startConnected = True
    nic_spec.device.connectable.allowGuestControl = True
    nic_spec.device.connectable.connected = False
    nic_spec.device.connectable.status = 'untried'
    nic_spec.device.wakeOnLanEnabled = True
    nic_spec.device.addressType = 'assigned'
 
    nic_changes.append(nic_spec)
    spec.deviceChange = nic_changes
    
    try:
        VM.ReconfigVM_Task(spec=spec)
        print (bcolors.OKGREEN + "NIC CARD with Network " + network + " added to VM " + VM_name + bcolors.ENDC)
        return

    except:
        print (bcolors.FAIL + "Error VM " + VM_name + bcolors.ENDC)
        return