Red Hat Training

A Red Hat training course is available for Red Hat Virtualization

2.14. Example: Creating a Virtual Machine NIC using Python

To ensure a newly created virtual machine has network access you must create and attach a virtual NIC.

Example 2.13. Creating a virtual machine NIC using Python

This Python example creates an NIC named nic1 and attaches it to the virtual machine named vm1. The NIC in this example:
  • Must be a virtio network device.
    nic_interface = "virtio"
  • Must be linked to the ovirtmgmt management network.
    nic_network = api.networks.get(name="ovirtmgmt")
These options are combined into an NIC parameter object, before using the add method of the virtual machine's nics collection to create the NIC.
from ovirtsdk.api import API
from ovirtsdk.xml import params

try:
    api = API (url="https://HOST",
               username="USER@DOMAIN",
               password="PASS",
               ca_file="ca.crt")

    vm = api.vms.get(name="vm1")

    nic_name = "nic1"
    nic_interface = "virtio"
    nic_network = api.networks.get(name="ovirtmgmt")

    nic_params = params.NIC(name=nic_name, interface=nic_interface, network=nic_network)

    try:
        nic = vm.nics.add(nic_params)
        print "Network interface '%s' added to '%s'." % (nic.get_name(), vm.get_name())
    except Exception as ex:
        print "Adding network interface to '%s' failed: %s" % (vm.get_name(), ex)

    api.disconnect()
              
except Exception as ex:
    print "Unexpected error: %s" % ex
If the add request is successful then the script will output:
Network interface 'nic1' added to 'vm1'.