Programster's Blog

Tutorials focusing on Linux, programming, and open-source

KVM - Add Disk

I run my virtual machines on SSD storage which is expensive compared to traditional HDD storage. Thus if a virtual machine needs a lot of storage, such as for a mirror, then I will give it an HDD disk to put the data on. Here's how to do just that.

Create the Disk

qemu-img create \
  -f qcow2 \
  -o lazy_refcounts=on,preallocation=metadata \

Attach the Disk

virsh attach-disk [vm ID] \
  --source /path/to/disk.qcow2 \
  --target vd[x] \
  --persistent \
  --subdriver qcow2

The previous command can be run to attach the disk whilst the VM Is running.

The path to the disk for source has to be an absolute path, not a relative one.

At this point the disk should show up in your VM if you run the command:

ls /dev/vd*

To use the disk we need to create a filesystem on it.

sudo mkfs -t ext4 /dev/vd[x]

Now we need a place to mount the disk and add it to our /etc/fstab so that it will mount on boot.

sudo mkdir /media/data

Then add the following to your fstab

/dev/vdb /media/data ext4 defaults 0 2

Now you can mount everything

sudo mount -a

Detach Disk

If you wish to remove a disk, you can do so like so:

sudo virsh detach-disk $GUEST_ID vd[x]
Last updated: 16th June 2021
First published: 16th August 2018