Manage KVM virtual machines¶
Part of the KVM overview. Start, stop, inspect, edit, clone, rename and delete VMs.
List, start, stop¶
virsh list # running
virsh list --all # everything defined
virsh start vm01
virsh shutdown vm01 # ACPI shutdown
virsh reboot vm01
virsh destroy vm01 # force off (like pulling the plug; does NOT delete anything)
virsh suspend vm01 # pause in memory
virsh resume vm01
virsh autostart vm01
virsh autostart --disable vm01
Details¶
virsh dominfo vm01
virsh domblklist vm01 --details
virsh domiflist vm01
virsh vcpuinfo vm01
virsh domstats vm01
virsh console vm01 # leave with Ctrl+]
ps -ef | grep '[v]m01' # the qemu process
If virsh console says Active console session exists for this domain, another session holds it; close that one (or kill it) first. If it says cannot find character device, the guest has no serial console configured: add a <serial> device and console=ttyS0 to the guest kernel command line (libvirt wiki).
Edit the definition¶
virsh edit vm01 # validates on save
virsh dumpxml vm01 > vm01.xml.bak.$(date +%Y%m%d.%H%M)
xmllint --noout vm01.xml # well-formed?
virt-xml-validate vm01.xml # schema-valid?
virsh define vm01.xml
Prefer virsh edit over hand-editing files in /etc/libvirt/qemu/; libvirt regenerates those.
Delete a VM¶
virsh destroy vm01 # if running
virsh undefine vm01 --remove-all-storage --managed-save --snapshots-metadata --nvram
--managed-saveavoidsRefusing to undefine while domain managed save image exists(or runvirsh managedsave-remove vm01).--nvramis needed for UEFI guests.- Omit
--remove-all-storageto keep the disks.
Clone¶
The source must be shut off. virt-clone generates new MAC addresses and disk files.
virt-clone --original vm01 --name vm02 --auto-clone
virt-clone --original vm01 --name vm02 --file /var/lib/libvirt/images/vm02.qcow2 # one disk
virt-clone --original vm01 --name vm02 --file /var/lib/libvirt/images/vm02-a.qcow2 --file /var/lib/libvirt/images/vm02-b.qcow2 # two disks
For a golden image, run virt-sysprep -d vm01 before cloning to strip SSH host keys, machine-id and logs. If the clone's interface comes up as eth1 because the old MAC is remembered in /etc/udev/rules.d/70-persistent-net.rules (older distributions), delete that file in the clone and reboot.
Rename¶
The VM must be shut off.
virsh domrename vm01 vm02
This does not rename the disk file. To rename it too:
sudo mv /var/lib/libvirt/images/vm01.qcow2 /var/lib/libvirt/images/vm02.qcow2
virsh edit vm02 # update <source file='...'/>