Skip to content

Instantly share code, notes, and snippets.

@bruceoutdoors
Created May 6, 2026 12:10
Show Gist options
  • Select an option

  • Save bruceoutdoors/5a0253a3f823d823b6591440dad00eec to your computer and use it in GitHub Desktop.

Select an option

Save bruceoutdoors/5a0253a3f823d823b6591440dad00eec to your computer and use it in GitHub Desktop.
Makes IP static for given virtual machine name in virt-manager
#!/bin/bash
# Check if VM name is provided
VM_NAME=$1
if [ -z "$VM_NAME" ]; then
echo "Makes IP static for given virtual machine name in virt-manager"
echo "Usage: $0 <vm_name>"
exit 1
fi
# 1. Get the MAC address and Network Name from the first interface
IFACE_INFO=$(virsh domiflist "$VM_NAME" | grep -E "network|bridge" | head -n 1)
MAC=$(echo "$IFACE_INFO" | awk '{print $5}')
NETWORK=$(echo "$IFACE_INFO" | awk '{print $3}')
if [ -z "$MAC" ] || [ -z "$NETWORK" ]; then
echo "Error: Could not find network info for '$VM_NAME'. Is the VM using a 'Network' source?"
exit 1
fi
# 2. Get the current IP address
# Try getting it from DHCP leases first, then fall back to the Guest Agent
IP=$(virsh domifaddr "$VM_NAME" --source lease | grep "$MAC" | awk '{print $4}' | cut -d'/' -f1)
if [ -z "$IP" ]; then
IP=$(virsh domifaddr "$VM_NAME" --source agent | grep "ipv4" | head -n 1 | awk '{print $4}' | cut -d'/' -f1)
fi
if [ -z "$IP" ]; then
echo "Error: Could not detect a running IP for '$VM_NAME'. Ensure the VM is running."
exit 1
fi
echo "VM: $VM_NAME | MAC: $MAC | Current IP: $IP | Network: $NETWORK"
echo "Applying static reservation..."
# 3. Add the DHCP host entry to the libvirt network
# --live updates the running network; --config makes it survive reboots
virsh net-update "$NETWORK" add ip-dhcp-host \
"<host mac='$MAC' name='$VM_NAME' ip='$IP' />" \
--live --config
if [ $? -eq 0 ]; then
echo "Success! $VM_NAME will now always receive $IP on the '$NETWORK' network."
else
echo "Failed. (Note: If the entry already exists, this command will error.)"
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment