Skip to content

Instantly share code, notes, and snippets.

@DavesCodeMusings
Last active May 2, 2022 00:20
Show Gist options
  • Select an option

  • Save DavesCodeMusings/d38b327062df1bf70085028e583eb1d3 to your computer and use it in GitHub Desktop.

Select an option

Save DavesCodeMusings/d38b327062df1bf70085028e583eb1d3 to your computer and use it in GitHub Desktop.
Create a new volume in a storage pool using libvirt-python API
#!/usr/bin/env python3
# Define a storage pool using the libvirt API.
# virsh vol-list <poolname> to verify.
# virsh vol-delete <volname> --pool <poolname> to remove.
import libvirt
import sys
import os
pool_name = "test"
vol_name = "test-vol"
vol_size = 2
vol_type = "qcow2"
# Use the type as the file extension.
vol_name = vol_name + "." + vol_type
vol_path = os.path.join("/var/lib/libvirt", pool_name, vol_name)
print("Connecting to API")
conn = None
try:
conn = libvirt.open("qemu:///system")
except libvirt.libvirtError as e:
print(repr(e), file=sys.stderr)
exit(1)
print("Using storage pool", pool_name)
pool = conn.storagePoolLookupByName(pool_name)
print("Creating storage volume", vol_name)
volumeXML = """
<volume>
<name>{0}</name>
<allocation>0</allocation>
<capacity unit="G">{1}</capacity>
<target>
<format type="{2}"/>
<path>{3}</path>
</target>
</volume>""".format(vol_name, vol_size, vol_type, vol_path)
pool.createXML(volumeXML, 0)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment