Files
loc_az_hci/scripts/fix/add-ssh-keys-to-dhcp-vms.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

201 lines
5.7 KiB
Bash
Executable File

#!/bin/bash
source ~/.bashrc
# Add SSH Keys to VMs that are already using DHCP
# Since VMs are already on DHCP, we just need to add SSH keys via cloud-init
set -euo pipefail
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 ""
echo -e "${BLUE}========================================${NC}"
echo -e "${BLUE}$1${NC}"
echo -e "${BLUE}========================================${NC}"
echo ""
}
PVE_USERNAME="${PVE_USERNAME:-root@pam}"
PVE_PASSWORD="${PVE_ROOT_PASS:-}"
PROXMOX_URL="${PROXMOX_ML110_URL:-https://192.168.1.206:8006}"
PROXMOX_NODE="${PROXMOX_NODE:-pve}"
SSH_KEY_FILE="$HOME/.ssh/id_ed25519_proxmox.pub"
# VM definitions: vmid name
VMS=(
"100 cloudflare-tunnel"
"101 k3s-master"
"102 git-server"
"103 observability"
)
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
}
add_ssh_key_to_vm() {
local vmid=$1
local name=$2
log_info "Adding SSH key to VM $vmid ($name)..."
if [ ! -f "$SSH_KEY_FILE" ]; then
log_error "SSH key file not found: $SSH_KEY_FILE"
return 1
fi
local tokens=$(get_api_token)
if [ -z "$tokens" ]; then
log_error "Failed to authenticate with Proxmox"
return 1
fi
local ticket=$(echo "$tokens" | cut -d'|' -f1)
local csrf_token=$(echo "$tokens" | cut -d'|' -f2)
# Read and encode SSH key
local ssh_key_content=$(cat "$SSH_KEY_FILE")
local ssh_key_b64=$(echo "$ssh_key_content" | base64 -w 0)
# Add SSH key via cloud-init
curl -s -k -X POST \
-H "Cookie: PVEAuthCookie=$ticket" \
-H "CSRFPreventionToken: $csrf_token" \
--data-urlencode "sshkeys=$ssh_key_b64" \
--data-urlencode "ciuser=ubuntu" \
"$PROXMOX_URL/api2/json/nodes/$PROXMOX_NODE/qemu/$vmid/config" > /dev/null
log_info "✓ SSH key added to VM $vmid"
}
discover_vm_ips() {
log_step "Discovering VM IPs via QEMU Guest Agent"
log_info "Waiting for VMs to apply cloud-init changes..."
sleep 10
log_info "Rebooting VMs to apply SSH keys..."
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 <<< "$vm_spec"
log_info "Rebooting 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/reboot" > /dev/null 2>&1 || true
done
log_info "Waiting 90 seconds for VMs to reboot and apply cloud-init..."
sleep 90
log_info "Discovering IPs via QEMU Guest Agent..."
source "$PROJECT_ROOT/scripts/lib/proxmox_vm_helpers.sh" 2>/dev/null || {
log_error "Helper library not found"
return 1
}
local all_ok=true
for vm_spec in "${VMS[@]}"; do
read -r vmid name <<< "$vm_spec"
local ip
ip="$(get_vm_ip_from_guest_agent "$vmid" 2>/dev/null || true)"
if [[ -n "$ip" ]]; then
log_info " ✓ VM $vmid ($name): $ip"
# Test SSH
if ssh -i "${SSH_KEY_FILE%.pub}" -o ConnectTimeout=5 -o StrictHostKeyChecking=no ubuntu@$ip "echo 'SSH OK'" &>/dev/null; then
log_info " ✓ SSH working!"
else
log_warn " ✗ SSH not working yet (may need more time)"
all_ok=false
fi
else
log_warn " ✗ VM $vmid ($name): IP not discovered (guest agent may need more time)"
all_ok=false
fi
done
if [ "$all_ok" = true ]; then
log_info ""
log_info "✓ All VMs have SSH access!"
else
log_warn ""
log_warn "Some VMs may need more time. Wait a few minutes and test again."
fi
}
main() {
log_step "Add SSH Keys to DHCP VMs"
log_info "Your VMs are already configured for DHCP - no IP conflicts!"
log_info "We just need to add SSH keys via cloud-init."
echo ""
if [ ! -f "$SSH_KEY_FILE" ]; then
log_error "SSH key file not found: $SSH_KEY_FILE"
exit 1
fi
log_step "Step 1: Adding SSH Keys via Cloud-Init"
for vm_spec in "${VMS[@]}"; do
read -r vmid name <<< "$vm_spec"
add_ssh_key_to_vm "$vmid" "$name" || log_warn "Failed to add SSH key to VM $vmid"
done
discover_vm_ips
log_step "Summary"
log_info "✓ SSH keys added via cloud-init"
log_info "✓ VMs are using DHCP (no IP conflicts)"
log_info "✓ IPs discovered via QEMU Guest Agent"
log_info ""
log_info "Your scripts already support dynamic IP discovery!"
log_info "Test SSH: ./scripts/ops/ssh-test-all.sh"
}
main "$@"