Skip to content

Instantly share code, notes, and snippets.

@joejulian
Last active December 26, 2016 07:04
Show Gist options
  • Save joejulian/f26e03cd399693a3454f to your computer and use it in GitHub Desktop.
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
#! /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())
@joejulian
Copy link
Author

Copied the constraint usage from anaconda. Seems to have fixed the constraint error.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment