#!/bin/bash source ~/.bashrc # Create Proxmox Mail Gateway VM via Proxmox API using ISO # Downloads ISO if needed, uploads to Proxmox, and creates VM automatically set -e # Colors RED='\033[0;31m' GREEN='\033[0;32m' YELLOW='\033[1;33m' BLUE='\033[0;34m' CYAN='\033[0;36m' 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 "${BLUE}[STEP]${NC} $1" } log_header() { echo -e "${CYAN}========================================${NC}" echo -e "${CYAN}$1${NC}" echo -e "${CYAN}========================================${NC}" } # Load environment variables if [ -f .env ]; then set -a source <(grep -v '^#' .env | grep -v '^$' | sed 's/#.*$//' | sed 's/^[[:space:]]*//;s/[[:space:]]*$//' | grep '=') set +a else log_error ".env file not found!" exit 1 fi # Configuration PVE_USERNAME="${PVE_USERNAME:-root@pam}" PVE_PASSWORD="${PVE_ROOT_PASS:-}" PROXMOX_HOST="${1:-192.168.1.206}" PROXMOX_URL="https://${PROXMOX_HOST}:8006" PROXMOX_NODE="${2:-pve}" STORAGE_POOL="${3:-local}" # PMG VM Configuration VMID=105 VM_NAME="proxmox-mail-gateway" CORES=2 MEMORY=4096 DISK_SIZE="50G" # ISO Configuration ISO_FILE="proxmox-mail-gateway_9.0-1.iso" ISO_URL="https://enterprise.proxmox.com/iso/proxmox-mail-gateway_9.0-1.iso" ISO_DIR="${4:-./downloads/iso}" ISO_PATH="${ISO_DIR}/${ISO_FILE}" # Get authentication ticket get_ticket() { local response=$(curl -k -s -d "username=$PVE_USERNAME&password=$PVE_PASSWORD" \ "$PROXMOX_URL/api2/json/access/ticket") local ticket=$(echo "$response" | grep -o '"ticket":"[^"]*' | cut -d'"' -f4) local csrf=$(echo "$response" | grep -o '"CSRFPreventionToken":"[^"]*' | cut -d'"' -f4) if [ -z "$ticket" ] || [ -z "$csrf" ]; then log_error "Failed to authenticate with Proxmox" return 1 fi echo "$ticket|$csrf" } # Download ISO if not present download_iso() { if [ -f "$ISO_PATH" ]; then log_info "ISO already exists locally: $ISO_PATH" ISO_SIZE=$(du -h "$ISO_PATH" | cut -f1) log_info "ISO size: $ISO_SIZE" return 0 fi log_step "Downloading PMG ISO..." log_info "URL: $ISO_URL" log_info "Destination: $ISO_PATH" log_warn "This may take several minutes depending on network speed..." # Create ISO directory if it doesn't exist mkdir -p "$ISO_DIR" # Download ISO with progress if command -v wget >/dev/null 2>&1; then wget --progress=bar:force -O "$ISO_PATH" "$ISO_URL" 2>&1 | grep --line-buffered -oP '\d+%' | while read -r line; do echo -ne "\r${GREEN}[INFO]${NC} Download progress: $line" done echo "" elif command -v curl >/dev/null 2>&1; then curl -L --progress-bar -o "$ISO_PATH" "$ISO_URL" else log_error "Neither wget nor curl is available. Cannot download ISO." return 1 fi if [ ! -f "$ISO_PATH" ]; then log_error "ISO download failed" return 1 fi ISO_SIZE=$(du -h "$ISO_PATH" | cut -f1) log_info "✓ ISO downloaded successfully: $ISO_SIZE" return 0 } # Check if ISO exists locally check_iso() { if [ ! -f "$ISO_PATH" ]; then log_warn "ISO file not found: $ISO_PATH" log_info "Attempting to download from: $ISO_URL" if ! download_iso; then log_error "Failed to download ISO. Please download manually and place it at: $ISO_PATH" exit 1 fi else log_info "Found ISO: $ISO_PATH" ISO_SIZE=$(du -h "$ISO_PATH" | cut -f1) log_info "ISO size: $ISO_SIZE" fi } # Check if ISO already exists in Proxmox iso_exists() { local auth=$1 local ticket=$(echo "$auth" | cut -d'|' -f1) local csrf=$(echo "$auth" | cut -d'|' -f2) local response=$(curl -k -s -H "Cookie: PVEAuthCookie=$ticket" \ -H "CSRFPreventionToken: $csrf" \ "$PROXMOX_URL/api2/json/nodes/$PROXMOX_NODE/storage/${STORAGE_POOL}/content") echo "$response" | python3 -c " import sys, json data = json.load(sys.stdin) isos = [f for f in data.get('data', []) if f.get('content') == 'iso' and '$ISO_FILE' in f.get('volid', '')] print('true' if isos else 'false') " 2>/dev/null || echo "false" } # Upload ISO to Proxmox upload_iso() { local auth=$1 local ticket=$(echo "$auth" | cut -d'|' -f1) local csrf=$(echo "$auth" | cut -d'|' -f2) log_step "Uploading ISO to Proxmox..." log_warn "This may take several minutes depending on ISO size and network speed..." # Upload ISO using multipart form local result=$(curl -k -X POST \ -H "Cookie: PVEAuthCookie=$ticket" \ -H "CSRFPreventionToken: $csrf" \ -F "content=iso" \ -F "filename=@$ISO_PATH" \ "$PROXMOX_URL/api2/json/nodes/$PROXMOX_NODE/storage/${STORAGE_POOL}/upload" 2>&1) if echo "$result" | grep -q "error"; then log_error "ISO upload failed: $result" return 1 fi log_info "✓ ISO uploaded successfully" return 0 } # Check if VM exists vm_exists() { local auth=$1 local vmid=$2 local ticket=$(echo "$auth" | cut -d'|' -f1) local csrf=$(echo "$auth" | cut -d'|' -f2) local response=$(curl -k -s -H "Cookie: PVEAuthCookie=$ticket" \ -H "CSRFPreventionToken: $csrf" \ "$PROXMOX_URL/api2/json/cluster/resources?type=vm") echo "$response" | python3 -c " import sys, json data = json.load(sys.stdin) vms = [v for v in data.get('data', []) if v.get('type') == 'qemu' and str(v.get('vmid')) == '$vmid'] print('true' if vms else 'false') " 2>/dev/null || echo "false" } # Create VM via API create_vm() { local auth=$1 local ticket=$(echo "$auth" | cut -d'|' -f1) local csrf=$(echo "$auth" | cut -d'|' -f2) log_step "Creating VM: $VM_NAME (ID: $VMID)..." # First, verify ISO exists in storage local iso_volid="${STORAGE_POOL}:iso/${ISO_FILE}" log_info "Using ISO: $iso_volid" # Strategy: Create VM with minimal config, then add hardware via separate API calls log_info "Step 1: Creating VM skeleton..." local create_response=$(curl -k -s -X POST \ -H "Cookie: PVEAuthCookie=$ticket" \ -H "CSRFPreventionToken: $csrf" \ -d "vmid=$VMID" \ -d "name=$VM_NAME" \ "$PROXMOX_URL/api2/json/nodes/$PROXMOX_NODE/qemu" 2>&1) if echo "$create_response" | grep -q '"errors"'; then log_error "Failed to create VM skeleton:" echo "$create_response" | python3 -c "import sys, json; d=json.load(sys.stdin); print(json.dumps(d.get('errors', {}), indent=2))" 2>/dev/null || echo "$create_response" return 1 fi log_info "✓ VM skeleton created" sleep 1 # Step 2: Configure basic VM settings log_info "Step 2: Configuring CPU and memory..." curl -k -s -X PUT \ -H "Cookie: PVEAuthCookie=$ticket" \ -H "CSRFPreventionToken: $csrf" \ -d "cores=$CORES" \ -d "memory=$MEMORY" \ -d "ostype=l26" \ -d "agent=1" \ "$PROXMOX_URL/api2/json/nodes/$PROXMOX_NODE/qemu/$VMID/config" > /dev/null 2>&1 # Step 3: Add disk log_info "Step 3: Adding disk..." local disk_response=$(curl -k -s -X PUT \ -H "Cookie: PVEAuthCookie=$ticket" \ -H "CSRFPreventionToken: $csrf" \ -d "scsi0=${STORAGE_POOL}:${DISK_SIZE}" \ "$PROXMOX_URL/api2/json/nodes/$PROXMOX_NODE/qemu/$VMID/config" 2>&1) if echo "$disk_response" | grep -q '"errors"'; then log_warn "Disk configuration warning (continuing anyway)" fi # Step 4: Add ISO log_info "Step 4: Adding ISO..." local iso_response=$(curl -k -s -X PUT \ -H "Cookie: PVEAuthCookie=$ticket" \ -H "CSRFPreventionToken: $csrf" \ -d "ide2=$iso_volid" \ "$PROXMOX_URL/api2/json/nodes/$PROXMOX_NODE/qemu/$VMID/config" 2>&1) if echo "$iso_response" | grep -q '"errors"'; then log_warn "ISO configuration warning (continuing anyway)" fi # Step 5: Add network (DHCP configuration) log_info "Step 5: Adding network (DHCP)..." local net_response=$(curl -k -s -X PUT \ -H "Cookie: PVEAuthCookie=$ticket" \ -H "CSRFPreventionToken: $csrf" \ -d "net0=model=virtio,bridge=vmbr0" \ "$PROXMOX_URL/api2/json/nodes/$PROXMOX_NODE/qemu/$VMID/config" 2>&1) if echo "$net_response" | grep -q '"errors"'; then log_warn "Network configuration warning (may need manual configuration)" fi # Step 6: Set boot order log_info "Step 6: Configuring boot order..." curl -k -s -X PUT \ -H "Cookie: PVEAuthCookie=$ticket" \ -H "CSRFPreventionToken: $csrf" \ -d "boot=order=ide2" \ "$PROXMOX_URL/api2/json/nodes/$PROXMOX_NODE/qemu/$VMID/config" > /dev/null 2>&1 # Step 7: Add tags log_info "Step 7: Adding tags..." curl -k -s -X PUT \ -H "Cookie: PVEAuthCookie=$ticket" \ -H "CSRFPreventionToken: $csrf" \ -d "tags=mail;security;gateway" \ "$PROXMOX_URL/api2/json/nodes/$PROXMOX_NODE/qemu/$VMID/config" > /dev/null 2>&1 # Verify VM config file was created sleep 2 local verify_response=$(curl -k -s -H "Cookie: PVEAuthCookie=$ticket" \ -H "CSRFPreventionToken: $csrf" \ "$PROXMOX_URL/api2/json/nodes/$PROXMOX_NODE/qemu/$VMID/config" 2>&1) if echo "$verify_response" | grep -q '"errors"'; then log_error "VM $VM_NAME was not created properly. Config file missing." log_error "Response: $verify_response" return 1 fi log_info "✓ VM $VM_NAME created successfully" return 0 } # Start VM start_vm() { local auth=$1 local ticket=$(echo "$auth" | cut -d'|' -f1) local csrf=$(echo "$auth" | cut -d'|' -f2) log_info "Starting VM $VMID..." local start_response=$(curl -k -s -X POST \ -H "Cookie: PVEAuthCookie=$ticket" \ -H "CSRFPreventionToken: $csrf" \ "$PROXMOX_URL/api2/json/nodes/$PROXMOX_NODE/qemu/$VMID/status/start") if echo "$start_response" | grep -q '"error"'; then log_warn "Failed to start VM $VMID: $start_response" return 1 fi log_info "✓ VM $VMID started" return 0 } main() { log_header "Create Proxmox Mail Gateway VM" echo "" if [ -z "$PVE_PASSWORD" ]; then log_error "PVE_ROOT_PASS not set in .env" exit 1 fi # Check/download ISO file check_iso echo "" # Authenticate log_step "Authenticating with Proxmox..." auth=$(get_ticket) if [ $? -ne 0 ]; then exit 1 fi log_info "✓ Authentication successful" echo "" # Check if VM already exists if [ "$(vm_exists "$auth" "$VMID")" = "true" ]; then log_warn "VM $VM_NAME (ID: $VMID) already exists. Skipping creation..." log_info "To recreate, delete the VM first via Proxmox Web UI or API" exit 0 fi # Check if ISO already uploaded if [ "$(iso_exists "$auth")" = "true" ]; then log_info "✓ ISO already exists in Proxmox storage" else # Upload ISO if ! upload_iso "$auth"; then log_error "Failed to upload ISO" exit 1 fi fi echo "" # Create VM log_step "Creating VM..." echo "" if create_vm "$auth"; then # Start VM start_vm "$auth" echo "" log_header "VM Creation Complete" echo "" log_info "Proxmox Mail Gateway VM has been created and started!" echo "" log_info "VM Details:" echo " - Name: $VM_NAME" echo " - ID: $VMID" echo " - Cores: $CORES" echo " - Memory: ${MEMORY}MB" echo " - Disk: $DISK_SIZE" echo " - Network: DHCP (vmbr0)" echo "" log_info "Next steps:" echo " 1. Access VM console via Proxmox Web UI: $PROXMOX_URL" echo " 2. Complete Proxmox Mail Gateway installation via console" echo " 3. Configure PMG after installation completes" echo "" else log_error "Failed to create VM $VM_NAME" exit 1 fi } main "$@"