Python libvirt API - creating a virtual machine

I am trying to create a python script to handle basic VM operations, such as: creating a virtual machine, deleting a virtual machine, starting, stopping, etc.

Currently, I’m rather stuck on create

From the command line you will do something like:

qemu-img create -f qcow2 vdisk.img <size>
virt-install --virt-type kvm --name testVM --ram 1024
 --cdrom=ubuntu.iso  --disk /path/to/virtual/drive,size=10,format=qcow2
 --network network=default --graphics vnc,listen=0.0.0.0 --noautoconsole
 --os-type=linux

And this will create a new virtual machine called testVMand install it on a previously definedvdisk.img

But I want to do all this in python; I know how to handle the second part:

  • start with XML template for VM
  • open a libvirt connection and use the connection handler to create the virtual machine

    But I'm interested in the first part, where you need to create a virtual disk.

Can I use it libvirt API calls?

, qemu-img create ?

+4
1

- , , - - .

libvirt .

libvirt.org: " - , , , . , , ."

, , quemu-img create. , .img( qemu-img); , qemu-img, .

, qemu-img

conn = libvirt.open()

pools = conn.listAllStoragePools(0)

for pool in pools:              

    #check if pool is active
    if pool.isActive() == 0:
        #activate pool
        pool.create()

    stgvols = pool.listVolumes()
    print('Storage pool: '+pool.name())
    for stgvol in stgvols :
        print('  Storage vol: '+stgvol)

:

def createStoragePool(conn):        
        xmlDesc = """
        <pool type='dir'>
          <name>guest_images_storage_pool</name>
          <uuid>8c79f996-cb2a-d24d-9822-ac7547ab2d01</uuid>
          <capacity unit='bytes'>4306780815</capacity>
          <allocation unit='bytes'>237457858</allocation>
          <available unit='bytes'>4069322956</available>
          <source>
          </source>
          <target>
            <path>/path/to/guest_images</path>
            <permissions>
              <mode>0755</mode>
              <owner>-1</owner>
              <group>-1</group>
            </permissions>
          </target>
        </pool>"""


        pool = conn.storagePoolDefineXML(xmlDesc, 0)

        #set storage pool autostart     
        pool.setAutostart(1)
        return pool

:

def createStoragePoolVolume(pool, name):    
        stpVolXml = """
        <volume>
          <name>"""+name+""".img</name>
          <allocation>0</allocation>
          <capacity unit="G">10</capacity>
          <target>
            <path>/path/to/guest_images/"""+name+""".img</path>
            <permissions>
              <owner>107</owner>
              <group>107</group>
              <mode>0744</mode>
              <label>virt_image_t</label>
            </permissions>
          </target>
        </volume>"""

        stpVol = pool.createXML(stpVolXml, 0)   
        return stpVol
+3

Source: https://habr.com/ru/post/1617237/


All Articles