Skip to content

Instantly share code, notes, and snippets.

@wiggin15
Created September 17, 2014 09:26
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save wiggin15/319b5e828c42af3aed40 to your computer and use it in GitHub Desktop.
Save wiggin15/319b5e828c42af3aed40 to your computer and use it in GitHub Desktop.
Add PCI passthrough device to a VM using pyvmomi
def add_pci_to_vm(host_object, vm_object, host_pci_dev):
"""
host_pci_dev must be one of the devices from the host_object.hardware.pciDevice list
which is configured as a PCI passthrough device
"""
pci_passthroughs = vm_object.environmentBrowser.QueryConfigTarget(host=None).pciPassthrough
systemid_by_pciid = {item.pciDevice.id: item.systemId for item in pci_passthroughs}
if host_pci_dev.id not in systemid_by_pciid:
raise Exception("Not a passthrough device")
# According to the documentation, the deviceId is a signed short but the server expects the PCI device ID
# to be unsigned. TODO the modulu here is because of this, but I think it's not needed
deviceId = hex(host_pci_dev.deviceId % 2**16).lstrip('0x')
backing = vim.VirtualPCIPassthroughDeviceBackingInfo(deviceId=deviceId,
id=host_pci_dev.id,
systemId=systemid_by_pciid[host_pci_dev.id],
vendorId=host_pci_dev.vendorId,
deviceName=host_pci_dev.deviceName)
hba_object = vim.VirtualPCIPassthrough(key=-100, backing=backing)
new_device_config = vim.VirtualDeviceConfigSpec(device=hba_object)
new_device_config.operation = "add"
vm_object.ReconfigVM_Task(spec=new_device_config)
@wiggin15
Copy link
Author

wiggin15 commented Apr 3, 2020

To get vm_object you can take a look at the pyvmomi community samples, or infi.pyvmomi_wrapper. Make sure it is not None. host_object can be the VM's runtime host - vm.summary.runtime.host. For host_pci_dev see the docstring.

@huchen2021
Copy link

what's docstring?

@huchen2021
Copy link

Does anyone know how to list VirtualPCIPassthrough's all VMs?

@huchen2021
Copy link

How to plugin dynamic Passthrough device to a VM using pyvmomi sdk? Does anyone know anything about this?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment