Commit bf777a27 authored by Vitaly Lipatov's avatar Vitaly Lipatov

pve: add functions with shared helpers for cluster scripts

Provides pvesh_cmd (uses ssh -n to avoid stdin consumption inside while-read loops), get_cluster_resources with caching, resolve_vmid that sets RES_TYPE/NODE/STATUS/NAME/POOL, and vm_cmd/vm_mgr helpers. Co-Authored-By: 's avatarClaude Opus 4.7 (1M context) <noreply@anthropic.com>
parent d8981dfe
# --- Shared helpers for PVE management scripts ---
# PVE API entry point (any cluster node with pvesh)
PVE_HOST="${PVE_HOST:-root@gefest}"
log() { echo "$(date '+%H:%M:%S') $*" ; }
fatal() { log "FATAL: $*" >&2 ; exit 1 ; }
# Run pvesh on PVE cluster node.
# -n: don't read stdin, otherwise ssh would consume it inside `while read` loops.
pvesh_cmd() { ssh -n "$PVE_HOST" "pvesh $*" ; }
# Get all cluster VM/CT resources as JSON
# Caches result in RES_JSON for repeated use within one script run
get_cluster_resources() {
if [ -z "$RES_JSON" ] ; then
RES_JSON=$(pvesh_cmd "get /cluster/resources --type vm --output-format json") || fatal "cannot get cluster resources"
fi
echo "$RES_JSON"
}
# Resolve VMID to its type, node, status, name, pool
# Sets: RES_TYPE (qemu|lxc), RES_NODE, RES_STATUS, RES_NAME, RES_POOL
# Usage: resolve_vmid 426
resolve_vmid() {
local vmid="$1"
[ -n "$vmid" ] || fatal "VMID required"
local json
json=$(get_cluster_resources)
local entry
entry=$(echo "$json" | jq -r --argjson id "$vmid" '.[] | select(.vmid == $id)') || fatal "jq parse error"
[ -n "$entry" ] || fatal "VMID $vmid not found in cluster"
RES_TYPE=$(echo "$entry" | jq -r '.type')
RES_NODE=$(echo "$entry" | jq -r '.node')
RES_STATUS=$(echo "$entry" | jq -r '.status')
RES_NAME=$(echo "$entry" | jq -r '.name // ""')
RES_POOL=$(echo "$entry" | jq -r '.pool // ""')
}
# Run command on the node where VM/CT lives (requires resolve_vmid first)
vm_cmd() { ssh "root@$RES_NODE" "$@" ; }
# Get the qm/pct command for the resolved resource type
vm_mgr() {
case "$RES_TYPE" in
qemu) echo "qm" ;;
lxc) echo "pct" ;;
*) fatal "unknown type: $RES_TYPE" ;;
esac
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment