10

I need to create a raw disk image for use in a virtual machine, but I need to create the partitions before creating the file system or installing the operating system.

Can anyone describe a process to do this?

3
  • Which virtual machine technology are you using? Because they have different disk formats (.vhd(x) for Microsoft's, .vmdk for VMware and so on)? I think you should create a VM of type you want with a Linux LiveCD .iso mounted and the virtual disk to be partitioned. There are a lot of guides on how to use a LiveCD to partition a disk (since there are so many variants of LiveCDs around you have to find an appropriate guide for a LiveCD you chose to use).
    – mprill
    Dec 26, 2012 at 23:30
  • Just a raw disk image, like when you dump a disk using a block copy tool like dd
    – Aethylred
    Dec 27, 2012 at 0:42

2 Answers 2

5

First create a blank raw disk image (25GB in this case):

    # dd if=/dev/zero of=disk.img bs=1024k seek=25600 count=0
    0+0 records in
    0+0 records out
    0 bytes (0 B) copied, 2.7301e-05 s, 0.0 kB/s
    # ls -lh
    total 2.0G
    -rw-r--r-- 1 root root  25G Dec 13 11:13 disk.img

Give it a partition table:

    # parted disk.img mklabel msdos

Mount it as a loopback device (the simplest way to define cylinders, heads, and sectors):

    # losetup -f disk.img
    # losetup -a
    /dev/loop0: [0801]:12059103 (/path/to/disk.img)

Check that it seems to be a valid block device:

    # fdisk /dev/loop0

    WARNING: DOS-compatible mode is deprecated. It's strongly recommended to
     switch off the mode (command 'c') and change display units to
     sectors (command 'u').

    Command (m for help): p

    Disk /dev/loop0: 26.8 GB, 26843545600 bytes
    255 heads, 63 sectors/track, 3263 cylinders
    Units = cylinders of 16065 * 512 = 8225280 bytes
    Sector size (logical/physical): 512 bytes / 512 bytes
    I/O size (minimum/optimal): 512 bytes / 512 bytes
    Disk identifier: 0x000db005

    Device Boot      Start         End      Blocks   Id  System

Then use fdisk to partition it as you wish:

    # fdisk /dev/loop0

When you're done you need to unloop the device (it will need unmapping and unmounting first):

# losetup -d /dev/loop0
5

Fully automated procedure

Create a my.img image with a single ext4 partition:

sudo apt-get install kpartx
img='my.img'
dd if=/dev/zero of="$img" bs=512 count=131072
printf 'o\nn\np\n1\n\n\nw\n' | fdisk "$img"
sudo kpartx -av "$img"
sudo mke2fs -t ext4 /dev/mapper/loop0p1
mkdir d
sudo mount /dev/mapper/loop0p1 d
# Do something to the ext partition.
sudo touch a
sudo umount d
sudo kpartx -dv "$img"

Tested on Ubuntu 14.04.

The "hard" parts are:

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .