#!/bin/bash set -Eeuo pipefail # The standard output is used to alter the domain's XML configuration. # Suppress all output to avoid interfering with libvirt's operation. exec > /dev/null function log () { echo "$@" >&2 } # This script is called by libvirt when a VM is started or stopped. # It is used to set up and tear down networking for the VM. # The script takes two arguments: the VM name and the action (start or stop). VM_NAME="$1" ACTION="$2" # Check if the networking configuration file exists for the VM if [ ! -f "/etc/libvirt-hooks/${VM_NAME}/iptables" ]; then log "No networking configuration found for VM '$VM_NAME'. Skipping." exit 0 fi if [ "$ACTION" = "started" ] || [ "$ACTION" = "reconnect" ] || [ "$ACTION" = "restore" ]; then log "Setting up networking for VM '$VM_NAME'..." # Set up iptables rules while read -r rule; do if [ -z "$rule" ]; then continue fi iptables $rule done < "/etc/libvirt-hooks/${VM_NAME}/iptables" log "Networking setup complete for VM '$VM_NAME'." elif [ "$ACTION" = "stopped" ] || [ "$ACTION" = "disconnect" ]; then log "Tearing down networking for VM '$VM_NAME'..." # Tear down iptables rules while read -r rule; do if [ -z "$rule" ]; then continue fi # Replace '-A'/'-I' with '-D' to delete the rule rule="${rule/-A/-D}" rule="${rule/-I/-D}" iptables $rule || log "Warning: Failed to delete iptables rule: iptables $rule" done < "/etc/libvirt-hooks/${VM_NAME}/iptables" log "Networking teardown complete for VM '$VM_NAME'." else log "Unknown action '$ACTION'. Supported actions are 'started', 'stopped', 'reconnect', and 'disconnect'." log "Skipping." fi exit 0