Files
loc_az_hci/scripts/deploy/recreate-vms-smaller-disks.sh
defiQUG c39465c2bd
Some checks failed
Test / test (push) Has been cancelled
Initial commit: loc_az_hci (smom-dbis-138 excluded via .gitignore)
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-02-08 09:04:46 -08:00

338 lines
11 KiB
Bash
Executable File

#!/bin/bash
source ~/.bashrc
# Recreate VMs with Smaller Disk Sizes
# Stops, deletes, and recreates VMs with optimized disk sizes
set -e
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PROJECT_ROOT="$(cd "$SCRIPT_DIR/../.." && pwd)"
# Load environment variables
if [ -f "$PROJECT_ROOT/.env" ]; then
set -a
source <(grep -v '^#' "$PROJECT_ROOT/.env" | grep -v '^$' | sed 's/#.*$//' | grep '=')
set +a
fi
# Colors
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m'
log_info() {
echo -e "${GREEN}[INFO]${NC} $1"
}
log_warn() {
echo -e "${YELLOW}[WARN]${NC} $1"
}
log_error() {
echo -e "${RED}[ERROR]${NC} $1"
}
log_step() {
echo -e "\n${BLUE}=== $1 ===${NC}"
}
# Proxmox configuration
PROXMOX_URL="${PROXMOX_ML110_URL:-https://192.168.1.206:8006}"
PVE_USERNAME="${PVE_USERNAME:-root@pam}"
PVE_PASSWORD="${PVE_ROOT_PASS:-}"
PROXMOX_NODE="${PROXMOX_NODE:-pve}"
TEMPLATE_VMID="${TEMPLATE_VMID:-9000}"
get_api_token() {
local response=$(curl -s -k --connect-timeout 10 --max-time 15 \
-d "username=$PVE_USERNAME&password=$PVE_PASSWORD" \
"$PROXMOX_URL/api2/json/access/ticket" 2>&1)
if echo "$response" | grep -q '"data"'; then
local ticket=$(echo "$response" | grep -o '"ticket":"[^"]*' | cut -d'"' -f4)
local csrf_token=$(echo "$response" | grep -o '"CSRFPreventionToken":"[^"]*' | cut -d'"' -f4)
echo "$ticket|$csrf_token"
else
echo ""
fi
}
stop_and_delete_vm() {
local vmid=$1
local name=$2
log_info "Stopping VM $vmid ($name)..."
local tokens=$(get_api_token)
local ticket=$(echo "$tokens" | cut -d'|' -f1)
local csrf_token=$(echo "$tokens" | cut -d'|' -f2)
# Check if VM exists
local vm_status=$(curl -s -k -H "Cookie: PVEAuthCookie=$ticket" \
-H "CSRFPreventionToken: $csrf_token" \
"$PROXMOX_URL/api2/json/nodes/$PROXMOX_NODE/qemu/$vmid/status/current" 2>&1)
if ! echo "$vm_status" | grep -q '"data"'; then
log_warn "VM $vmid does not exist, skipping"
return 0
fi
# Stop VM if running
local status=$(echo "$vm_status" | python3 -c "import sys, json; print(json.load(sys.stdin).get('data', {}).get('status', 'unknown'))" 2>/dev/null)
if [ "$status" = "running" ]; then
log_info "Stopping VM $vmid..."
curl -s -k -X POST -H "Cookie: PVEAuthCookie=$ticket" \
-H "CSRFPreventionToken: $csrf_token" \
"$PROXMOX_URL/api2/json/nodes/$PROXMOX_NODE/qemu/$vmid/status/stop" > /dev/null
# Wait for VM to stop
local wait_count=0
while [ $wait_count -lt 30 ]; do
sleep 2
local current_status=$(curl -s -k -H "Cookie: PVEAuthCookie=$ticket" \
-H "CSRFPreventionToken: $csrf_token" \
"$PROXMOX_URL/api2/json/nodes/$PROXMOX_NODE/qemu/$vmid/status/current" | \
python3 -c "import sys, json; print(json.load(sys.stdin).get('data', {}).get('status', 'unknown'))" 2>/dev/null)
if [ "$current_status" = "stopped" ]; then
break
fi
wait_count=$((wait_count + 1))
done
if [ $wait_count -ge 30 ]; then
log_error "VM $vmid did not stop in time"
return 1
fi
fi
# Delete VM
log_info "Deleting VM $vmid..."
local delete_response=$(curl -s -k -X DELETE \
-H "Cookie: PVEAuthCookie=$ticket" \
-H "CSRFPreventionToken: $csrf_token" \
"$PROXMOX_URL/api2/json/nodes/$PROXMOX_NODE/qemu/$vmid" 2>&1)
if echo "$delete_response" | grep -q '"data"'; then
log_info "VM $vmid deleted successfully"
return 0
else
log_error "Failed to delete VM $vmid: $delete_response"
return 1
fi
}
create_vm_with_smaller_disk() {
local vmid=$1
local name=$2
local ip=$3
local gateway=$4
local cores=$5
local memory=$6
local disk=$7
local bridge=$8
log_info "Creating VM $vmid ($name) with ${disk} disk..."
local tokens=$(get_api_token)
local ticket=$(echo "$tokens" | cut -d'|' -f1)
local csrf_token=$(echo "$tokens" | cut -d'|' -f2)
if [ -z "$ticket" ] || [ -z "$csrf_token" ]; then
log_error "Failed to get API tokens"
return 1
fi
# Clone VM from template
log_info "Cloning from template $TEMPLATE_VMID..."
local clone_response=$(curl -s -k -X POST \
-H "Cookie: PVEAuthCookie=$ticket" \
-H "CSRFPreventionToken: $csrf_token" \
-d "newid=$vmid" \
-d "name=$name" \
"$PROXMOX_URL/api2/json/nodes/$PROXMOX_NODE/qemu/$TEMPLATE_VMID/clone" 2>&1)
if ! echo "$clone_response" | grep -q '"data"'; then
log_error "Failed to clone VM: $clone_response"
return 1
fi
log_info "VM cloned successfully, waiting for clone to complete..."
sleep 5
# Wait for clone to finish
local wait_count=0
while [ $wait_count -lt 30 ]; do
local vm_check=$(curl -s -k -H "Cookie: PVEAuthCookie=$ticket" \
-H "CSRFPreventionToken: $csrf_token" \
"$PROXMOX_URL/api2/json/nodes/$PROXMOX_NODE/qemu/$vmid/config" 2>&1)
if echo "$vm_check" | grep -q '"data"'; then
break
fi
sleep 2
wait_count=$((wait_count + 1))
done
# Configure VM with smaller disk
log_info "Configuring VM $vmid (CPU: $cores, RAM: ${memory}MB, Disk: $disk)..."
# Stop VM if it started automatically
curl -s -k -X POST -H "Cookie: PVEAuthCookie=$ticket" \
-H "CSRFPreventionToken: $csrf_token" \
"$PROXMOX_URL/api2/json/nodes/$PROXMOX_NODE/qemu/$vmid/status/stop" > /dev/null 2>&1
sleep 3
# Get current disk configuration
local current_config=$(curl -s -k -H "Cookie: PVEAuthCookie=$ticket" \
-H "CSRFPreventionToken: $csrf_token" \
"$PROXMOX_URL/api2/json/nodes/$PROXMOX_NODE/qemu/$vmid/config")
local current_disk=$(echo "$current_config" | python3 -c "import sys, json; d=json.load(sys.stdin).get('data', {}); print(d.get('scsi0', ''))" 2>/dev/null)
# Extract storage pool from current disk or use default
local storage_pool="local-lvm"
if echo "$current_disk" | grep -q ':'; then
storage_pool=$(echo "$current_disk" | cut -d':' -f1)
fi
# Delete old disk and create new smaller one
log_info "Removing old disk and creating new ${disk} disk..."
# Remove old disk
curl -s -k -X PUT -H "Cookie: PVEAuthCookie=$ticket" \
-H "CSRFPreventionToken: $csrf_token" \
-d "scsi0=" \
"$PROXMOX_URL/api2/json/nodes/$PROXMOX_NODE/qemu/$vmid/config" > /dev/null 2>&1
sleep 2
# Create new disk with smaller size using the disk creation endpoint
log_info "Creating new ${disk} disk..."
local disk_create=$(curl -s -k -X POST \
-H "Cookie: PVEAuthCookie=$ticket" \
-H "CSRFPreventionToken: $csrf_token" \
-d "size=$disk" \
-d "format=raw" \
-d "storage=$storage_pool" \
"$PROXMOX_URL/api2/json/nodes/$PROXMOX_NODE/qemu/$vmid/config" 2>&1)
# If that doesn't work, try setting it directly in config
if ! echo "$disk_create" | grep -q '"data"'; then
log_info "Trying alternative method: setting disk in config..."
curl -s -k -X PUT -H "Cookie: PVEAuthCookie=$ticket" \
-H "CSRFPreventionToken: $csrf_token" \
-d "scsi0=$storage_pool:vm-$vmid-disk-0,iothread=1,size=$disk" \
"$PROXMOX_URL/api2/json/nodes/$PROXMOX_NODE/qemu/$vmid/config" > /dev/null 2>&1
fi
# Configure CPU and memory
curl -s -k -X PUT -H "Cookie: PVEAuthCookie=$ticket" \
-H "CSRFPreventionToken: $csrf_token" \
-d "cores=$cores" \
-d "memory=$memory" \
"$PROXMOX_URL/api2/json/nodes/$PROXMOX_NODE/qemu/$vmid/config" > /dev/null
# Configure network
curl -s -k -X PUT -H "Cookie: PVEAuthCookie=$ticket" \
-H "CSRFPreventionToken: $csrf_token" \
-d "net0=virtio,bridge=$bridge,firewall=1" \
"$PROXMOX_URL/api2/json/nodes/$PROXMOX_NODE/qemu/$vmid/config" > /dev/null
# Configure QEMU Guest Agent
curl -s -k -X PUT -H "Cookie: PVEAuthCookie=$ticket" \
-H "CSRFPreventionToken: $csrf_token" \
-d "agent=1" \
"$PROXMOX_URL/api2/json/nodes/$PROXMOX_NODE/qemu/$vmid/config" > /dev/null
# Configure cloud-init
log_info "Configuring cloud-init (user: ubuntu, IP: $ip/24)..."
curl -s -k -X PUT -H "Cookie: PVEAuthCookie=$ticket" \
-H "CSRFPreventionToken: $csrf_token" \
--data-urlencode "ipconfig0=ip=$ip/24,gw=$gateway" \
-d "ciuser=ubuntu" \
"$PROXMOX_URL/api2/json/nodes/$PROXMOX_NODE/qemu/$vmid/config" > /dev/null
log_info "VM $vmid configured successfully with ${disk} disk"
return 0
}
main() {
log_step "Recreating VMs with Smaller Disk Sizes"
if [ -z "$PVE_PASSWORD" ]; then
log_error "PVE_ROOT_PASS not set in .env"
exit 1
fi
log_warn "This will DELETE and RECREATE all VMs with smaller disks!"
log_warn "All data on these VMs will be lost!"
# Check for --yes flag to skip confirmation
if [ "$1" != "--yes" ] && [ "$1" != "-y" ]; then
echo ""
read -p "Are you sure you want to continue? (yes/no): " confirm
if [ "$confirm" != "yes" ]; then
log_info "Cancelled by user"
exit 0
fi
else
log_info "Auto-confirmed (--yes flag provided)"
fi
# VM definitions with smaller disk sizes
# Format: vmid name ip gateway cores memory_mb disk_size bridge
local vms=(
"100 cloudflare-tunnel 192.168.1.60 192.168.1.254 2 4096 20G vmbr0"
"101 k3s-master 192.168.1.188 192.168.1.254 4 8192 40G vmbr0"
"102 git-server 192.168.1.121 192.168.1.254 4 8192 50G vmbr0"
"103 observability 192.168.1.82 192.168.1.254 4 8192 100G vmbr0"
)
# Step 1: Stop and delete existing VMs
log_step "Step 1: Stopping and Deleting Existing VMs"
for vm_spec in "${vms[@]}"; do
read -r vmid name ip gateway cores memory disk bridge <<< "$vm_spec"
stop_and_delete_vm "$vmid" "$name"
sleep 2
done
# Step 2: Recreate VMs with smaller disks
log_step "Step 2: Creating VMs with Smaller Disks"
for vm_spec in "${vms[@]}"; do
read -r vmid name ip gateway cores memory disk bridge <<< "$vm_spec"
create_vm_with_smaller_disk "$vmid" "$name" "$ip" "$gateway" "$cores" "$memory" "$disk" "$bridge"
sleep 3
done
# Step 3: Start all VMs
log_step "Step 3: Starting All VMs"
local tokens=$(get_api_token)
local ticket=$(echo "$tokens" | cut -d'|' -f1)
local csrf_token=$(echo "$tokens" | cut -d'|' -f2)
for vm_spec in "${vms[@]}"; do
read -r vmid name ip gateway cores memory disk bridge <<< "$vm_spec"
log_info "Starting VM $vmid ($name)..."
curl -s -k -X POST -H "Cookie: PVEAuthCookie=$ticket" \
-H "CSRFPreventionToken: $csrf_token" \
"$PROXMOX_URL/api2/json/nodes/$PROXMOX_NODE/qemu/$vmid/status/start" > /dev/null
sleep 2
done
log_step "Recreation Complete!"
log_info "All VMs recreated with smaller disk sizes:"
log_info " VM 100: 20G (was 40G)"
log_info " VM 101: 40G (was 80G)"
log_info " VM 102: 50G (was 100G)"
log_info " VM 103: 100G (was 200G)"
log_info "Total saved: 210GB"
}
main "$@"