I wanted to alter a file that was a disk image for a KVM virtual
machine. With a physical machine I use
dd fairly often to save and
alter the partition table and boot loader. I wanted to do that to a KVM
image. The problem being that when you use
dd to write to a file, when
dd is done it truncates the file. So I would lay down a new partition
table and boot loader on my KVM image and find the image was now only a
few kilobytes long. It used to be 20 gigabytes in size!
To do this we need to use the loop device:
# dd if=/dev/zero of=/var/lib/libvirt/images/foo.img bs=1024 count=20971520 # losetup /dev/loop0 /var/lib/libvirt/images/foo.img # dd if=/tmp/bar.img of=/dev/loop0
Now you can use
fdisk or other tools to examine the hard disk image on
/dev/loop0. When you are done, tear down the loopback.
# losetup -d /dev/loop0
Now boot your KVM.
Why do I like to do this? Think about automated ways to install DBan. Or to laydown a gPXE bootloader to reinstall or reprovision the machine. Fixing a corrupt partition table or MBR. Doing things this way allows for a high level of automation.