Created
May 20, 2025 08:55
-
-
Save NotYusta/15516e2251544d7750890a7d726ce7ad to your computer and use it in GitHub Desktop.
Import Proxmox VM Image with URL
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/bash | |
VMID=$1 | |
IMAGE_URL=$2 | |
STORAGE_TARGET=$3 | |
DISK_LABEL=$4 | |
DISK_SLOT=${5:-""} | |
if [ $# -lt 4 ]; then | |
echo "Usage: $0 <vmid> <image_url> <storage_target> <disk_label> [<disk_slot>]" | |
exit 1 | |
fi | |
# Validate storage exists | |
pvesm status | grep -q "^$STORAGE_TARGET" || { | |
echo "Error: Storage '$STORAGE_TARGET' not found." | |
exit 1 | |
} | |
# Find storage path | |
STORAGE_PATH=$(grep -A 3 "^dir: $STORAGE_TARGET" /etc/pve/storage.cfg | grep "path" | awk '{print $2}') | |
[ -z "$STORAGE_PATH" ] && { | |
echo "Failed to determine the storage path for '$STORAGE_TARGET'." | |
exit 1 | |
} | |
# Ensure disk directory exists | |
DISK_PATH="$STORAGE_PATH/images/$VMID" | |
mkdir -p "$DISK_PATH" | |
# Set disk file path | |
DISK_FILE="$DISK_PATH/$DISK_LABEL.qcow2" | |
# Download if not exists | |
if [ ! -f "$DISK_FILE" ]; then | |
echo "Downloading image to $DISK_FILE..." | |
curl -sLo "$DISK_FILE" "$IMAGE_URL" | |
[ $? -ne 0 ] && { | |
echo "Error downloading image." | |
exit 1 | |
} | |
else | |
echo "Disk file already exists at $DISK_FILE, skipping download." | |
fi | |
# Check if already attached | |
CONFIG_FILE="/etc/pve/qemu-server/$VMID.conf" | |
DISK_REF="$STORAGE_TARGET:$VMID/$DISK_LABEL.qcow2" | |
if grep -q "$DISK_REF" "$CONFIG_FILE"; then | |
echo "Disk already attached to VM $VMID, skipping attachment." | |
exit 0 | |
fi | |
# Determine available slot if not specified | |
if [ -z "$DISK_SLOT" ]; then | |
for i in {0..20}; do | |
if ! grep -q "^scsi$i:" "$CONFIG_FILE"; then | |
DISK_SLOT=$i | |
break | |
fi | |
done | |
[ -z "$DISK_SLOT" ] && { | |
echo "Error: No available SCSI slots found." | |
exit 1 | |
} | |
else | |
if grep -q "^scsi$DISK_SLOT:" "$CONFIG_FILE"; then | |
echo "Error: scsi$DISK_SLOT is already used." | |
exit 1 | |
fi | |
fi | |
# Attach the disk | |
echo "Attaching disk to scsi$DISK_SLOT..." | |
qm set "$VMID" --scsi"$DISK_SLOT" "$DISK_REF" | |
[ $? -ne 0 ] && { | |
echo "Failed to attach disk." | |
exit 1 | |
} | |
echo "Disk successfully attached to VM $VMID in SCSI slot $DISK_SLOT." |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment