Knowledge Base

Preserving for the future: Shell scripts, AoC, and more

Create, attach, detach disk to vm in kvm on command line

In kvm, let's say you want to create a new disk and attach it to a virtual machine. You could use Virtual Machine Manager. But for the command line, here is a quick way how to do it.

Create a disk

Create a qcow2 disk that is fully allocated. When I tried with disks that were not fully allocated, the vm would only see the 200K or so and would not let me write a partition table large enough to do anything.

time qemu-img create -f qcow2 /var/lib/libvirt/images/vmname-vdb.qcow2 22000M -o preallocation=full

Attach a disk

You can omit the flags as needed, if you don't want to update the virtual machine's definition, or --config. And some of these are probably redundant, but they did not throw errors for me and I wanted the change to be immediate and persistent upon vm reboot, so I leave them all in.

virsh attach-disk --domain vmname /var/lib/libvirt/images/vmname-vdb.qcow2 --target vdb --persistent --config --live

Detach a disk

Same thing as the attaching, only you don't include the --target flag.

virsh detach-disk --domain vmname /var/lib/libvirt/images/vmname-vdb.qcow2 --persistent --config --live

References

Weblinks

Man pages

  1. qemu-img

Comments