Convert image of a partition into image of a disk with partition table

You can do this on the host machine. Most tools like fdisk will operate on files, and kpartx gives you access to partitions in a file.

  1. Create a new empty 100GiB sparse image (make this slightly bigger than the size of the partition image)

    dd if=/dev/zero of=myvm.img bs=1G count=0 seek=100
    
  2. Partition the image file with fdisk

    fdisk myvm.img
    
  3. Make the partitions in the image file available is individual devices

    sudo kpartx -a myvm.img
    
  4. Copy the partition image into the partition

    sudo cp image.bin /dev/mapper/loop0p1
    
  5. Extend the filesystem to fill the entire partition

    sudo resize2fs /dev/mapper/loop0p1
    
  6. Close the partitions

    sudo kpartx -d myvm.img
    
  7. Dismantle the loopback device

    sudo losetup -D
    

I'm sure the original problem was solved long ago, but for anybody with a similar problem:

One way to avoid copying the whole image would be to create a .vmdk format image that refers to separate extent files for the partition table and for the partition contents.

I have this snippet lying around in a .vmdk file from a test I did a while ago:

RW 63 FLAT "parttable.bin" 0
RW 585937489 FLAT "partition-image.bin" 63

This means that the 63 sectors starting from offset 0 are read from the raw file "parttable.bin", but sector 63 and upwards come from the raw partition dump "partition-image.bin". (Of course, replace 63 with the actual offset to the first partition, usually 2048 these days).

The end result is that, from inside VBox, it looks like you have prepended the partition table on to the front of the partition image, without having to do the lengthy copy operation.

Partition the drive from within the VM and, if you get your offsets right, you should see your partition image contents inside the newly-created partition.


Interesting problem. Here's what I would do:

  1. Create the VM with a disk appropriately large then boot it from a recovery CD.
  2. Gain access to your existing disk image somehow (nfs, cifs, etc.).
  3. Create the partitions you'll need on the VM's local disk.
  4. Use dd to write the partition image into the partition on the vm disk.

After this is done you'll need to update your boot loader. Assuming you're using GRUB, mount the newly written partition then chroot into it and run update-grub (be careful though, you may need to adjust its config files before it will work right).

Good luck!