Automating LVM with Python

Hello! We will see how to automate logical volume management by writing a python code,

To get idea about creating logical volumes by commands and also integrating it with Hadoop you can read it here.

So, here we are creating a python code that will give us options to perform some operations related to LVM by integrating Linux commands for LVM into it using os or subprocess module of python.

We are creating a small menu from which user has to select options. Following is the python code,

from subprocess import getoutput
from os import system
print("""------------------ LVM with Python ----------------
1. Create Physical Volume (PV)
2. Create Volume Group (VG)
3. Craete Logical Volume (LV)
4. Format and Mount a logical Volume
5. Extend logical Volume size
6. Display PV
7. Display VG
8. Display LV
0. Exit """)
ch = int(input("Select option: "))
if ch==1:
dev = input("Enter disk or device name: ")
print(getoutput(f"pvcreate {dev}"))
elif ch==2:
pvnames = ''
pvname = input("Enter PV name: ")
pvnames += " " + pvname
check = input("Wnat to give more PV (Y/N): ")
if check not in ['Y','y']:
vgname = input("Give a Volume Group name: ")
print(getoutput(f"vgcreate {vgname} {pvnames}"))
elif ch==3:
vgname = input("Enter VG to be used: ")
lvname = input("Give a name to LV: ")
size = input("Eneter size you want for LV: ")
print(getoutput(f"lvcreate --size {size} --name {lvname} {vgname}"))
elif ch==4:
lvpath = input("Enter the LV path (/dev/vgname/lvname): ")
print(getoutput(f"mkfs.ext4 {lvpath}"))
folder = input("Enter the directory path to mount on: ")
getoutput(f"mount {lvpath} {folder}")
print("Mounted successfully!")
elif ch==5:
lvpath = input("Enter the LV path (/dev/vgname/lvname): ")
size = input("Enter size you want to add: ")
print(getoutput(f"lvextend --size +{size} {lvpath}"))
print(getoutput(f"resize2fs {lvpath}"))
elif ch==6:
elif ch==7:
elif ch==8:
elif ch==0:
input("Enter to continue...")

If we test this code, we will get output shown in the screenshots below, (rhel8)

That’s all,

Thank You!

Tech and Programming, MLOps, DevOps Assembly Lines, Hybrid Multi Cloud, Flutter and Ansible Automation