read

This small post shows my Bash script to direct attach a HDD of SSD in Proxmox to a VM

Don't like scrips? This are the manual steps: link

#!/bin/bash

# Function to list available disks
list_disks() {
    echo "Available disks:"
    ls /dev/disk/by-id/
}

# Function to attach disk to VM
attach_disk() {
    read -p "Enter the VM ID: " vm_id
    read -p "Enter the SCSI number to attach the disk to (e.g., 5): " scsi_number
    read -p "Enter the disk ID to attach (from the list above): " disk_id

    # Construct command to attach disk to VM
    command="qm set $vm_id -scsi$scsi_number /dev/disk/by-id/$disk_id"

    # Execute command
    echo "Attaching disk to VM..."
    $command
}

# Function to detach disk from VM
detach_disk() {
    read -p "Enter the VM ID: " vm_id

    # Get list of attached SCSI devices for the specified VM
    attached_devices=$(qm config $vm_id | grep 'scsi')

    if [ -z "$attached_devices" ]; then
        echo "No disks attached to VM $vm_id."
    else
        echo "Attached SCSI devices for VM $vm_id:"
        echo "$attached_devices"

        read -p "Enter the SCSI device number to detach (e.g., 5): " device_name

        # Parse SCSI ID from the device name
        scsi_id=$(echo "$device_name" | grep -o '[0-9]\+')

        # Construct command to detach disk from VM
        command="qm unlink $vm_id --idlist scsi$scsi_id"

        # Execute command
        echo "Detaching disk from VM..."
        $command
    fi
}

# Main function
main() {
    echo "1. Attach disk to VM"
    echo "2. Detach disk from VM"
    read -p "Enter your choice (1 or 2): " choice

    case $choice in
        1)
            list_disks
            attach_disk
            ;;
        2)
            detach_disk
            ;;
        *)
            echo "Invalid choice. Exiting."
            ;;
    esac
}

# Call main function
main

To make your bash script executable e.g. after creating and saving the script in nano or other editor on the Linux machine

chmod +x your_script_name.sh    

Or just download (extract zip before use): Download script

Blog Logo

Vincentde Koning

The world is a playground!


Published

Image

DE KONING

Projects, Adventures and Experiments

Back to Overview