Last active
December 26, 2016 07:04
-
-
Save joejulian/f26e03cd399693a3454f to your computer and use it in GitHub Desktop.
Python utility to maximize the root partition of a vm image for cloud-init
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#! /opt/pyparted/bin/python | |
import parted | |
import os | |
import sys | |
import dbus | |
def ask_udisk2(mountpath): | |
bus = dbus.SystemBus() | |
udisks2obj = bus.get_object('org.freedesktop.UDisks2', '/org/freedesktop/UDisks2') | |
udisks2om = dbus.Interface(udisks2obj, 'org.freedesktop.DBus.ObjectManager') | |
udisks2 = udisks2om.GetManagedObjects() | |
def find_mounted_partition(mountpath, objects): | |
for k in objects.keys(): | |
try: | |
if 'org.freedesktop.UDisks2.Filesystem' in [str(x) for x in objects[k].keys()]: | |
for mountpoint_b in objects[k]['org.freedesktop.UDisks2.Filesystem']['MountPoints']: | |
mountpoint = ''.join([chr(x) for x in mountpoint_b if x]) | |
if mountpoint == mountpath: | |
return k | |
except: | |
pass | |
def find_partition_device(partition, objects): | |
table = objects[partition]['org.freedesktop.UDisks2.Partition']['Table'] | |
blockdev = objects[table]['org.freedesktop.UDisks2.Block']['Device'] | |
return ''.join([chr(x) for x in blockdev if x]) | |
return find_partition_device(find_mounted_partition(mountpath,udisks2),udisks2) | |
def main(): | |
device = parted.getDevice(ask_udisk2('/')) | |
disk = parted.Disk(device) | |
constraint = parted.Constraint(device=disk.device) | |
try: | |
disk.maximizePartition(disk.partitions[1], constraint) | |
disk.commit() | |
except Exception as i: | |
if 'reboot' in str(i): | |
return 2 | |
print("Partition resize failed, {}".format(i)) | |
return 1 | |
print("Partition resized.") | |
return 0 | |
if __name__ == "__main__": | |
sys.exit(main()) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Copied the constraint usage from anaconda. Seems to have fixed the constraint error.