Monday, August 6, 2012

Mounting a Linux KVM image with an LVM partition

Problem:
In RedHat, how do you mount a KVM image with an LVM partition? Some of the files in the image, like "/etc/sysconfig/ifcfg-eth0" & "/etc/sysconfig/network"  need to be edited before use.

Solution:
From the KVM host, use a combination of "kpartx" & "lvchange" command line tools.

Procedure:
1. Install kpartx rpm through yum.
yum install kpartx

2. Install lvm2 rpm through yum.
yum install lvm2

3. Use "kpartx" to read partition tables & create device maps of your image.
kpartx -av  <image path>.img

Example:
[root@test1-server ~]# kpartx -av /home/images/test1.img
add map loop0p1 (253:6): 0 1024000 linear /dev/loop0 2048
add map loop0p2 (253:7): 0 30428928 linear /dev/loop0 1026048

4. Use "pvscan"  to see your LVM block devices for physical volume.
 Example:
[root@test1-server ~]# pvscan
  PV /dev/mapper/loop0p2   VG vg_or2svmqawmgr1   lvm2 [14.51 GiB / 0    free]

5. Use "vgscan"  to see your LVM physical volumes & volume groups.
Example:
[root@test1-server ~]# vgscan
  Reading all physical volumes.  This may take a while...
  Found volume group "vg_test1" using metadata type lvm2

6. Use "lvscan"  to see your LVM block devices for logical volumes.
Example:
[root@test1-server ~]# lvscan
  inactive          '/dev/vg_test1/lv_root' [10.75 GiB] inherit
  inactive          '/dev/vg_test1/lv_swap' [3.75 GiB] inherit

7. Use "lvchange" to activate the logical volume, to make it useable.
lvchange -ay <volume group name>

Example:
[root@or14svm-rsvr3 vm_xml_files]# lvchange -ay vg_test1
[root@test1-server ~]# lvscan
  ACTIVE          '/dev/vg_test1/lv_root' [10.75 GiB] inherit
  ACTIVE          '/dev/vg_test1/lv_swap' [3.75 GiB] inherit 

8. Create the directory for mounting the logical volume, then mount it, and start editing your files.
Example:
mkdir /mnt/partition
mount /dev/vg_test1/lv_root /mnt/partition
cd /mnt/partition 
ls

 
Reverse Procedure:
1. Unmount the logical volume.
Example:
cd $HOME
umount /mnt/partition

2. Use "lvchange" to deactivate the logical volume.
lvchange -an <volume group name>

Example:
[root@or14svm-rsvr3 vm_xml_files]# lvchange -an vg_test1
[root@test1-server ~]# lvscan

  inactive          '/dev/vg_test1/lv_root' [10.75 GiB] inherit
  inactive          '/dev/vg_test1/lv_swap' [3.75 GiB] inherit

3. Use "vgchange" to deactivate the volume group.
lvchange -an <volume group name>

Example:
[root@test1-server ~]# vgchange -an vg_test1
  0 logical volume(s) in volume group "vg_test1" now active

4. Use "kpartx" to delete device maps of your image.
kpartx -dv  <image path>.img

Example:
[root@test1-server ~]# kpartx -dv /home/images/test1.img
del devmap : loop0p2
del devmap : loop0p1
loop deleted : /dev/loop0


Reference:
http://support.citrix.com/article/CTX117791/