Automating LV Partition using Python-Script

LVM (Diagram created using Canva)

Let us suppose we have two HDs (Physical Volumes) sdc and sdb of sizes 20 GB and 40 GB respectively. And we want to store a file of say 30 GB. But we don’t have an HD of 20 GB specifically. So one possible solution for this is two combines both the HDs in a box and when we do so, we’ll get one HD of 60 GB where we can store our 30 GB file. That box is known as the Volume Group. And the partition created in a VG is known as Logical Volume. This whole concept is known as LVM (Logical Volume Management). The concept of LVM allows us to increase or decrease the size on the fly.

Now usually there are a few commands which one needs to run in order to create an LV. I have created a python program which to some extent automates the whole process.

Before we look at that program, let us look at the commands one needs to run to create an LV:

1. pvcreate /dev/sdc (to convert the HD into a physical volume)

2. pvdisplay /dev/sdc (to display the details of the given PV)

3. vgcreate <name_of_VG> /dev/sdc (to create a VG from the PV. Here multiple PVs can be used to create a VG)

4. lvcreate — size <size in GB> — name <name of lv> <name of vg> (to create a partition)

5. lvdisplay vg_name/lv_name (to see the details of created lv)

6. mkfs.ext4 /dev/vg_name/lv_name

7. mount /dev/vg_name-lv/name /folder_name

Steps to follow to extend the LV size:

1. lvextend — size +<size in GB> /dev/vg_name/lv_name (to extend lv size)

2. resize2fs /dev/vg_name/lv_name (to format only the newly added part)

Steps to follow to reduce the LV size:

1. unmount /<mounted folder name> (to un-mount the folder)

2. e2sck –f /dev/vg_name/lv_name (to clean the inode table)

3. resize2fs /dev/mapper/vg_name-lv_name <new size in GB>

4. lvreduce — size /dev/mapper/vg_name-lv_name

5. mount /dev/vg_name-lv/name /folder_name

As you can see the LVM creation process involves a lot of steps. In the hopes of reducing the time taken to manually run the above commands, I have tried to create a program that can reduce this time.

Output:

Thank you for taking out time to read this blog!

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store