====== Ubuntu - KVM - Add Disk Image ======
This is useful when you for example want to expand the disk space of your virtual machine when it is using LVM, or if you want to add a swap disk to a virtual machine.
Note that you can also create a swap file instead of a disk, however, this is an example for adding the disk.
===== Requirements =====
* Host running KVM and virsh
* Virtual Machine to add disk to
The example VM is named **example-vm** in virsh (domain).
----
===== Create and attach the disk image =====
Execute these steps on the KVM hypervisor host.
cd to the folder where you store your disk images:
cd /var/lib/libvirt/images/
----
===== Create the new disk image =====
sudo qemu-img create -f raw example-vm-swap.img 1G
We use **qemu-img** to **create** a new **raw** disk image with a size of 1 GB.
----
===== Attach the disk to the example virtual machine using virsh =====
virsh attach-disk example-vm --source /var/lib/libvirt/images/example-vm-swap.img --target vdb --persistent
We use virsh to attach the disk image **/var/lib/libvirt/images/example-vm-swap** as a **virtio** (**/dev/vdb**) disk to the domain (vm) **example-vm**.
The **--persistent** option updates the domain xml file with an element for the newly attached disk.
Note that if you already have a **/dev/vdb** disk you need to change **vdb** to a free device like **vdc** or **vdd**.
----
===== Reboot the Virtual Machine =====
Reboot so that the kernel sees the new disk.
Execute this in the virtual machine.
sudo reboot
----
===== Partition the drive =====
Partition the drive with **cfdisk**.
For our example we use filesystem type 82 (linux/linux swap):
Execute this in the virtual machine.
cfdisk /dev/vdb
Format the disk as swap:
mkswap /dev/vdb1
or format it as ext4:
mkfs.ext4 /dev/vdb1
----
===== Make the swap active =====
swapon /dev/vdb1
or mount the partition:
mkdir /mnt/new-disk
mount /dev/vdb1 /mnt/new-disk
----
===== Make the new disk persistant =====
Add to /etc/fstab for reboot persistence:
/dev/vdb1 swap swap defaults 0 0
or for the ext4 disk:
/dev/vdb1 /mnt/new-disk ext4 defaults 0 0
That's it. You've now created, attached, formatted and mounted a new disk in your VM.
----
===== References =====
* qemu-img man page [http://linux.die.net/man/1/qemu-img]
* virsh-attach doc page [http://builder.virt-tools.org/artifacts/libvirt-virshcmdref/html/sect-attach-disk.html]