handle kvm static ip adresses

Nov. 27, 2018    Tags: virsh  kvm

I did a lot of work with libvirt and kvm and for some hosts I wanted to have a fixed IP address but not configured on the host itself. I wanted to get it from dhcp. In the end there are two options to solve this Problem/Feature. But first we need to choose which net-list setup to use.

To get an overview we can do the following:

virsh net-list

Name                 State      Autostart     Persistent
----------------------------------------------------------
 default              active     no            yes

I use default most of the time. If you don’t want to use it, choose a different name from the list (if you have some).

Edit virsh net-list directly.

virsh net-edit default

If you have executed this command the first time your default editor opens something similar to this:

<network>
  <name>default</name>
  <uuid>UUID</uuid>
  <forward mode="nat">
  <bridge delay="0" name="virbr0" stp="on">
  <mac address="MAC">
  <ip address="192.168.123.1" netmask="255.255.255.0">
    <dhcp>
      <range end="192.168.123.254" start="192.168.123.200">
    </range></dhcp>
  </ip>
</mac></bridge></forward></network>

Now its possible to add the hsots manually. They can be added in the <dhcp>...</dhcp> tags below the <range>...</range>. Here you can add a line like this:

<host ip="192.168.123.10" mac="52:54:00:5e:b2:d9" name="hostname-01">
</host>

If you have added your hosts you have to “restart” somehow the network adapter of virsh:

virsh net-destroy default
virsh net-start default

That’s it. If you now restart your virtual machine or just do a dhclient INTERFACE you should see the IP.

Use a one in all call.

Second possibility is to use a one in all call. With this call you don’t need to destroy and start the network adapter. It’s all done by virsh.


virsh net-update default add-last ip-dhcp-host --xml "<host ip="192.168.122.60" mac="52:54:00:5e:b3:e9" name="hostname-02">" --live --config
</host>

This command adds the new host in xml syntax to your default live configuration.

We can double check if the entry really exists:


virsh net-edit default
....

<dhcp>
  <range end="192.168.123.254" start="192.168.123.200">
  <host ip="192.168.123.10" mac="52:54:00:5e:b2:d9" name="hostname-01">
  <host ip="192.168.122.60" mac="52:54:00:5e:b3:e9" name="hostname-02">
</host></host></range></dhcp>

As you see it’s there.

I like the second part more than the first one. It’s more simple and easy and you don’t have to restart the network adapter.