---
title: "Add KVM Network With Virsh"
date: 2021-10-16
draft: false
tags: ["linux", "kvm", "libvirt", "virsh"]
authors: ["trent"]
post: 25
---
date: 2021-10-16

## Introduction
This is a short and sweet walk-through for how to create
a new network for `libvirt` for `kvm`, from the command line,
using `virsh`.

## Name Resolution
Let's start with name resolution.

* Install `libnss-libvirt`:
```shell
apt install libnss-libvirt
```

* In `/etc/nsswitch.conf`, add `libvirt` to hosts key.
```cfg
# /etc/nsswitch.conf
# change this
...
hosts:          files dns mymachines
...
# to this
...
hosts:          files libvirt dns mymachines
...
```

## Starter XML
You could dumpxml on the existing _default_ network:
```shell
virsh net-dumpxml default > foonet.xml
```
Then, edit foonet.xml:

* remove the network uuid
* change the network name to taste
* remove the bridge mac
* change the bridge name to taste
* change the bridge ip address and dhcp range to taste

```xml
<!-- foonet.xml -->
<network>
  <name>foonet</name>
  <forward mode='nat'>
    <nat>
      <port start='1024' end='65535'/>
    </nat>
  </forward>
  <bridge name='virbr101' stp='on' delay='0'/>
  <ip address='10.55.44.1' netmask='255.255.255.0'>
    <dhcp>
      <range start='10.55.44.2' end='10.55.44.254'/>
    </dhcp>
  </ip>
</network>
```

## Define The Network
With the above xml file: `virsh net-define foonet.xml`

The network definition can now be found in `/etc/libvirt/qemu/networks/foonet.xml`
```xml
<!-- /etc/libvirt/qemu/networks/foonet.xml -->
<!--
WARNING: THIS IS AN AUTO-GENERATED FILE. CHANGES TO IT ARE LIKELY TO BE
OVERWRITTEN AND LOST. Changes to this xml configuration should be made using:
  virsh net-edit foonet
or other application using the libvirt API.
-->

<network>
  <name>foonet</name>
  <uuid>e6e40bfc-d449-4043-924c-ca0f0edf4210</uuid>
  <forward mode='nat'>
    <nat>
      <port start='1024' end='65535'/>
    </nat>
  </forward>
  <bridge name='virbr111' stp='on' delay='0'/>
  <mac address='52:54:00:49:a7:f8'/>
  <ip address='10.55.44.1' netmask='255.255.255.0'>
    <dhcp>
      <range start='10.55.44.2' end='10.55.44.254'/>
    </dhcp>
  </ip>
</network>
```

You could also start the network without defining it
using `virsh net-create foonet.xml`.

## Start/Stop
* Start the network
    * `virsh net-start foonet`
* Stop the network
    * `virsh net-destroy foonet`
* Undefine the network
    * `virsh net-undefine foonet`
* Autostart the network
    * `virsh net-autostart foonet`
* Disable autostart for the network
    * `virsh net-autostart foonet --disable`

Tab completion is you friend!
