handle kvm static ip adresses

Nov. 27, 2018    Tags: kvm  virsh

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:

  <forward mode="nat">
  <bridge delay="0" name="virbr0" stp="on">
  <mac address="MAC">
  <ip address="" netmask="">
      <range end="" start="">

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

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

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="" mac="52:54:00:5e:b3:e9" name="hostname-02">" --live --config

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

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

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.