Skip to content

Instantly share code, notes, and snippets.

@bgulla
Created October 16, 2024 16:57
Show Gist options
  • Save bgulla/addde54833c076996ffc42f9ad625d30 to your computer and use it in GitHub Desktop.
Save bgulla/addde54833c076996ffc42f9ad625d30 to your computer and use it in GitHub Desktop.
Proxmox VM & Disk Script
#!/bin/bash
# Script to delete a Proxmox VM and all associated hard disks.
# Usage:
# ./delete_vm_with_disks.sh <vmid> - Deletes the specified VM after user confirmation.
# ./delete_vm_with_disks.sh <vmid> --force - Force deletes the specified VM without confirmation.
#
# Arguments:
# <vmid> : The ID of the Proxmox VM to delete.
# --force : Optional argument to skip the confirmation prompt.
#
# Note: The script will identify and delete all disks associated with the VM
# from the Proxmox storage.
#
# Example:
# ./delete_vm_with_disks.sh 100 - Deletes VM with ID 100 after user confirmation.
# ./delete_vm_with_disks.sh 100 --force - Force deletes VM with ID 100.
# Check if VM ID is provided as an argument
if [ -z "$1" ]; then
echo "Usage: $0 <vmid> [--force]"
exit 1
fi
VMID=$1
FORCE=$2
# Check if the VM exists
if ! qm status $VMID > /dev/null 2>&1; then
echo "VM with ID $VMID does not exist."
exit 1
fi
# Get the VM name
VM_NAME=$(qm config $VMID | grep '^name:' | awk '{print $2}')
# If --force is not provided, ask for confirmation
if [ "$FORCE" != "--force" ]; then
echo "You are about to delete VM ID: $VMID, Name: $VM_NAME and its associated disks."
read -p "Are you sure? (y/n): " CONFIRMATION
if [ "$CONFIRMATION" != "y" ]; then
echo "Aborted."
exit 0
fi
fi
echo "Deleting VM $VMID and its associated disks..."
# Get list of hard disks attached to the VM
DISKS=$(qm config $VMID | grep '^scsi\|^ide\|^sata\|^virtio' | awk -F: '{print $2}' | awk '{print $1}')
# Remove VM
qm stop $VMID
qm destroy $VMID --purge
# Loop through the disk paths and delete them
for DISK in $DISKS; do
echo "Deleting disk $DISK..."
# Remove the disk
if [[ $DISK == */* ]]; then
# Example: local-lvm:vm-100-disk-0
IFS=':' read -ra STORAGE_DISK <<< "$DISK"
STORAGE="${STORAGE_DISK[0]}"
DISK_NAME="${STORAGE_DISK[1]}"
# Remove disk from storage
if pvesm list $STORAGE | grep -q "$DISK_NAME"; then
pvesm free "$DISK"
echo "Disk $DISK removed."
else
echo "Disk $DISK not found in storage $STORAGE."
fi
fi
done
echo "VM $VMID and all associated disks have been deleted."
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment