#!/bin/bash # Set a primary VM to use first NVIDIA card as PCI Passthrough # And REMOVE those 2 PCI devices from any other VM # mReschke 2025-03-16 # Input primary_vmid="$1" primary=109 # Validate if [ "$primary_vmid" == "" ]; then echo "You must provide a VMID you want to be the seconday" exit 1 fi # Define PCI devices to add/remove hostpci0="0000:81:00,pcie=1,x-vga=1" hostpci1="0000:04:00.3,pcie=1" # Get all VMID from qm list vmids=($(qm list | tail -n +2 | cut -d\ -f8)) # Loop each VM and remove our pci devices if exist found_primary=0 for vmid in "${vmids[@]}" do echo "Analyzing VMID $vmid" if [ "$vmid" == "$primary_vmid" ]; then found_primary=1 fi # TODO check status # qm status 102 | cut -d: -f2 | xargs # will be running or stopped # if running and PCI device exist, do NOT remove it # and if I can't remove it, do NOT add it second VM # Remove hostpci0 if matches our desired device if result=$(qm config $vmid | grep $hostpci0); then echo " VMID $vmid has option $result" qm set $vmid --delete hostpci0 echo " VMID $vmid removed hostpci0" fi # Remove hostpci1 is matches our desired device if result=$(qm config $vmid | grep $hostpci1); then echo " VMID $vmid has option $result" qm set $vmid --delete hostpci1 echo " VMID $vmid removed hostpci1" fi done # Finally add our PIC devices to the desired VMID if [ "$found_primary" == 1 ]; then echo echo "Setting primary VM to $primary_vmid" qm set $primary_vmid -hostpci0 $hostpci0 qm set $primary_vmid -hostpci1 $hostpci1 else echo "The primary VMID $primary_vmid was not found in qm list, not setting primary" exit 1 fi