Skip to content

Instantly share code, notes, and snippets.

@dcode
Created June 3, 2023 16:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dcode/9198f35b64f00e8bf2cdda12e3ed739a to your computer and use it in GitHub Desktop.
Save dcode/9198f35b64f00e8bf2cdda12e3ed739a to your computer and use it in GitHub Desktop.
Just a snippet of code to upload a VM image to libvirt using python
#!/bin/env python3
import libvirt
import pathlib
conn = libvirt.open("qemu:///system")
template_pool = conn.storagePoolLookupByName("default")
image_filename = "fedora-cloud-base-38-x86_64.qcow2"
spool_file = pathlib.Path("Fedora-Cloud-Base-38-1.6.x86_64.qcow2")
# Size from output of `qemu-img info --output=json Fedora-Cloud-Base-38-1.6.x86_64.qcow2`
image_size = 497291264
image_vsize = 5368709120
stgvol_xml = f"""
<volume>
<name>{image_filename}</name>
<allocation>{ image_size }</allocation>
<capacity unit="bytes">{image_vsize}</capacity>
</volume>"""
stgvol = template_pool.createXML(stgvol_xml, 0)
def stream_handler(stream, data, file_):
return file_.read(data)
stream = conn.newStream(0)
stgvol.upload(stream, 0, 0)
with spool_file.open(mode="rb") as f:
stream.sendAll(stream_handler, f)
stream.finish()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment