Friday, April 10, 2015

How to make a DHCP reservation for a kvm/libvirt host using virsh

It is very useful to reserve DHCP addresses for guest virtual machines. Here is a quick rundown of how to do it.

Run virsh

# virsh
Welcome to virsh, the virtualization interactive terminal.

Type:  'help' for help with commands
       'quit' to quit

virsh # net-list
 Name                 State      Autostart     Persistent
----------------------------------------------------------
 default              active     yes           yes

Once you are in virsh run net-list to figure out the list of networks you have. Usually you only have one as in this case. Go ahead and edit it.


virsh # net-edit default

This will pop you into your default editor. I changed mine to be nano. Edit the part that says dhcp or add it and make sure everything is correct. You can get the host mac by editing the specific vm's XML configuration file. To do that you can run the command "edit examplevm1" and just look for the MAC address.

<network>
  <name>default</name>
  <uuid>969e94f2-f6bb-4436-8195-51603fd79225</uuid>
  <forward mode='nat'>
    <nat>
      <port start='1024' end='65535'/>
    </nat>
  </forward>
  <bridge name='virbr0' stp='on' delay='0'/>
  <mac address='52:54:00:60:bc:01'/>
  <ip address='192.168.5.1' netmask='255.255.255.0'>
    <dhcp>
      <range start='192.168.5.100' end='192.168.5.254'/>
      <host mac='52:54:00:11:11:11' name='examplevm1' ip='192.168.5.10'/>
      <host mac='52:54:00:22:22:22' name='examplevm2' ip='192.168.5.20'/>    </dhcp>
  </ip>
</network>

Now the most annoying thing is you need to make sure these changes take hold. You can reboot all the VMs (pain in the butt) or use this script to remove and reattach each VM's network interface. The VMs will lose connectivity for a bit though.



No comments: