Migrate live system from single disk to LVM on RAID 1 (on Debian Jessie)

This assumes that the two drives are /dev/sda and /dev/sdb.
Where /dev/sda is the existing drive and /dev/sdb is the new drive,
and that the system partition is sda1/sdb1.

Copy the partition table from /dev/sda to /dev/sdb

sfdisk -d /dev/sda | sfdisk --force /dev/sdb

 

Set the filesystem type to “fd” (Linux raid autodetect)

sfdisk --change-id /dev/sdb 1 fd

 

Zero the superblock to make sure that mdadm will not detect an existing volume

mdadm --zero-superblock /dev/sdb1

 

Create the RAID 1 with the new disk only

mdadm --create /dev/md0 --level=1 --raid-disks=2 missing /dev/sdb1

 

Add the raid to mdadm.conf so that it will be configured automatically on boot

mdadm --examine --scan >> /etc/mdadm/mdadm.conf

 

Create the physical volume on the new raid volume

pvcreate /dev/md0

 

Create a volume group on the new physical volume

vgcreate vg_hostname /dev/md0

 

Create a logical volume on then new volume group

lvcreate -L 100G -n root vg_hostname

 

Create an ext4 filesystem on the logical volume

mkfs.ext4 /dev/vg_hostname/root

 

Mount the new filesystem

mount /dev/vg_hostname/root /mnt

 

Copy the old system files

rsync -auxHAXSv --exclude=/dev/* --exclude=/proc/* --exclude=/sys/* --exclude=/tmp/* --exclude=/mnt/* --exclude=/afs/* / /mnt/

 

Modify /etc/fstab, the line for / should be

/dev/vg_hostname/root / ext4    errors=remount-ro 0       1

 

Create /etc/grub.d/09-lvm with contents:

#!/bin/sh
exec tail -n +3 $0

menyentry 'New system' --class gnu-linux --class gnu --class os {
    insmod part_msdos
    insmod diskfilter
    insmod mdraid1x
    insmod lvm
    insmod ext2
    set root='lvm/vg_hostname-root'
    linux /boot/vmlinuz-$(uname -r) root=/dev/mapper/vg_hostname-root ro
    initrd /boot/initrd.img-$(uname -r)
}

 

Add the following to /etc/default/grub:

GRUB_PRELOAD_MODULES="lvm"

 

Update the grub configuration files:

update-grub

 

Update the initramfs

update-initramfs -c -k $(uname -r) -u

 

Reboot and it should now boot from the LVM volume

reboot

Verify that we have booted from the LVM volume

mount
# the output should contain the following
/dev/mapper/vg_hostname-root on / type ext4 (rw,relatime,errors=remount-ro,data=ordered)
  If everything is ok we can continue with adding the old drive to the raid. Change the partition type to Linux raid autodetect

sfdisk –change-id /dev/sda 1 fd 

Add the old drive to the raid:

mdadm --add /dev/md0 /dev/sda1

 

Update grub config files and initramfs

update-grub
update-initramfs -c -k $(uname -r) -u

 

Install grub to the devices.

grub-install --recheck /dev/sda
grub-install --recheck /dev/sdb