Skip to content

Instantly share code, notes, and snippets.

@ralvares
Created February 7, 2025 09:20
Show Gist options
  • Save ralvares/a54d3d28bc4235d390c31f42705ee5ac to your computer and use it in GitHub Desktop.
Save ralvares/a54d3d28bc4235d390c31f42705ee5ac to your computer and use it in GitHub Desktop.
How to Create and Attach a New Network to KVM VMs Using virsh

How to Create and Attach a New Network to KVM VMs Using virsh

1. Create a New Libvirt Network

1.1 Define the Network in XML

Create a new file called new-network.xml with the following content:

<network>
  <name>custom-net</name>
  <bridge name='virbr10'/>
  <forward mode='nat'/>
  <ip address='192.168.100.1' netmask='255.255.255.0'/>
</network>

1.2 Define and Start the Network

Run the following commands to create and activate the network:

# Define the new network
virsh net-define new-network.xml

# Start the network
virsh net-start custom-net

# Make it persistent
virsh net-autostart custom-net

Verify the network is active:

virsh net-list --all

2. Attach the New Network to OpenShift VMs

2.1 List Running VMs

To confirm your VMs are running, use:

virsh list

Example output:

 Id   Name            State
-------------------------------
 2    ocp-master-0    running
 3    ocp-master-1    running
 4    ocp-master-2    running
 5    ocp-compute-0   running
 6    ocp-compute-1   running
 7    ocp-compute-2   running

2.2 Attach the Network to Each VM

Run the following loop to attach the custom-net network to all OpenShift VMs:

for vm in ocp-master-0 ocp-master-1 ocp-master-2 ocp-compute-0 ocp-compute-1 ocp-compute-2; do
  virsh attach-interface --domain $vm --type network --source custom-net --model virtio --persistent
done

This will add a new network interface to each VM.

2.3 Verify the Interface is Added

To confirm that the network interface has been added, check the interface list of any VM:

virsh domiflist ocp-master-0

Example output:

Interface  Type       Source     Model    MAC
---------------------------------------------------
vnet0      network    default    virtio   52:54:00:12:34:56
vnet1      network    custom-net virtio   52:54:00:65:43:21
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment