Monday, November 18, 2024

How to Exporting and Importing KVM Virtual Machines on AlmaLinux 9 and Rocky Linux 9

The seamless migration and backup of virtual machines (VMs) are crucial for maintaining system stability and data integrity. This article provides a detailed walkthrough of exporting and importing Kernel-based Virtual Machines (KVMs) on AlmaLinux 9 and Rocky Linux 9, offering both command-line instructions and a robust bash script for automation. The process involves two key steps: backing up the VM's disk image and exporting its configuration data. This allows for efficient restoration, either on the same host or a different one, significantly reducing downtime and the effort associated with rebuilding VMs from scratch.

Understanding the KVM Environment and Virtual Machine Identification

Before embarking on the export and import procedures, it's essential to understand how KVM manages virtual machines and how to identify their key attributes. The virsh command-line utility serves as the primary interface for managing KVM VMs. To list all VMs, including those that are currently shut down, execute the following command:

      virsh list --all
    

This will produce a table displaying the ID and name of each VM along with its current state (running, shut off, etc.). For detailed information about a specific VM's configuration, use the dumpxml command. This command outputs the VM's configuration in XML format, providing a comprehensive view of all its settings:

      virsh dumpxml <VM_Name>
    

Replace <VM_Name> with the actual name of the virtual machine. Redirecting the output to a file is useful for archiving:

      virsh dumpxml AlmaLinux9 > AlmaLinux9.xml
    

Alternatively, a graphical user interface (GUI) provides a more visual approach to managing KVM VMs. The virt-manager tool offers a user-friendly environment, where you can readily access the XML configuration details of your VMs by selecting the "XML" tab within the "Show Virtual Hardware" section. This provides a similar level of detail to the command-line method, but in a more visually intuitive manner.

Locating the Virtual Machine Disk Image

The disk image file, typically stored in the qcow2 format, contains the virtual hard drive of your VM. By default, these images reside in the /var/lib/libvirt/images/ directory. However, customized installation procedures might place them elsewhere. To definitively identify the location of the disk image associated with a specific VM, use the following command:

      virsh dumpxml <VM_Name> | grep -i "source"
    

This command searches the XML configuration output for the <source> tag, which specifies the path to the disk image. The output will resemble:

      <source file='/var/lib/libvirt/images/AlmaLinux9.qcow2'/>
    

For situations where VMs might be scattered across various locations, a more comprehensive script is needed to identify all disk image paths:

      VM_NAMES=($(virsh list --all | awk '(NR>2)' | awk '{print $2}'))
for VM in ${VM_NAMES[@]}; do
  DISK_PATH=$(virsh dumpxml ${VM} | grep -i "<source file")
  echo "${VM} ${DISK_PATH}"
done | column -t
    

This script iterates through all listed VMs and extracts the disk image path, providing a clear mapping between VM name and disk location. This is particularly useful for managing numerous VMs where manual identification would be time-consuming and error-prone.

Exporting the Virtual Machine: A Two-Step Process

Exporting a KVM VM involves two distinct actions: exporting the configuration data and backing up the disk image. These actions are independent, allowing for flexible backup strategies.

  1. Exporting the Domain Configuration: The VM's configuration, including memory allocation, CPU settings, network interfaces, and other crucial parameters, is captured in an XML file using the virsh dumpxml command:

          virsh dumpxml <VM_Name> > /path/to/backup/<VM_Name>.xml
        

    This command exports the VM's configuration to an XML file located in the specified backup directory. Replacing /path/to/backup/ with your chosen backup location and <VM_Name> with the VM's name is crucial.

  2. Backing Up the Disk Image: The actual contents of the VM's virtual hard drive, stored in the qcow2 image file, are copied to the backup location using the cp command:

          sudo cp /var/lib/libvirt/images/<disk_image_name.qcow2> /path/to/backup/
        

    Remember to replace /var/lib/libvirt/images/<disk_image_name.qcow2> with the actual path to the disk image file as determined in the previous section.

Importing the Virtual Machine: Restoring the VM from Backup

Importing a previously exported KVM VM is a mirror image of the export process. It consists of two steps: restoring the disk image and importing the configuration.

  1. Restoring the Disk Image: The backup of the disk image is copied back to the default location or a new designated location:

          sudo cp /path/to/backup/<disk_image_name.qcow2> /var/lib/libvirt/images/
        

    Again, ensure the correct paths are used.

  2. Importing the Domain Configuration: Finally, the VM's configuration is imported using the virsh define command:

          virsh define /path/to/backup/<VM_Name>.xml
        

    This command reads the XML configuration file and creates a new VM based on the settings within the file. The VM will be added to the list of managed VMs, ready for use.

Automating the Export and Import Process with a Bash Script

Manual execution of these commands for numerous VMs is time-consuming. To streamline this process, the following bash script automates both the export and import operations:

      #!/usr/bin/env bash

if [[ ${UID} -ne 0 ]]; then
  echo "[EXIT] This script must be run as root."
  exit 1
fi

function export_vm() {
  read -p "Enter the export destination directory: " EXPORT_DIR
  [[ -d ${EXPORT_DIR} ]] || mkdir -p ${EXPORT_DIR}

  VM_NAMES=($(virsh list --all | awk '(NR>2)' | awk '{print $2}'))
  for VM in ${VM_NAMES[@]}; do
    virsh dumpxml ${VM} > ${EXPORT_DIR}/${VM}.xml
    DISK_PATH=$(virsh dumpxml ${VM} | grep -i "<source file" | cut -d '"' -f 2)
    sudo cp "${DISK_PATH}" "${EXPORT_DIR}/"
  done
  echo "VM configurations and disk images exported to ${EXPORT_DIR}"
}

function import_vm() {
  read -p "Enter the import source directory: " IMPORT_DIR
  [[ -d ${IMPORT_DIR} ]] || { echo "Directory not found"; exit 1; }

  sudo rsync -av "${IMPORT_DIR}/" "/var/lib/libvirt/"
  for XML_FILE in ${IMPORT_DIR}/*.xml; do
    virsh define "${XML_FILE}"
  done
  echo "VMs imported successfully."
  virsh list --all
}

case $1 in
  export ) export_vm ;;
  import ) import_vm ;;
  * ) echo "Usage: $0 [export|import]" ;;
esac
    

This script provides functions for both exporting and importing, prompting the user for the necessary directory paths. The rsync command is used for efficient and robust file transfer, ensuring data integrity. Error handling is incorporated to enhance script reliability. To use the script, save it as kvm_export_import.sh, make it executable (chmod +x kvm_export_import.sh), and run it with either export or import as arguments.

Conclusion

This comprehensive guide has provided a clear and practical approach to exporting and importing KVM virtual machines on AlmaLinux 9 and Rocky Linux 9. Through the use of both command-line tools and an automated bash script, managing the backup and restoration of your VMs becomes significantly easier and more efficient. This robust methodology reduces the potential for data loss and simplifies the management of your virtual infrastructure. The flexibility offered by the script allows for adapting the export and import processes to different environments and backup strategies, offering a solid foundation for reliable VM management.

0 comments:

Post a Comment