Fediversity/deployment/proxmox/remove.sh

138 lines
3.1 KiB
Bash
Executable file

#!/usr/bin/env sh
set -euC
################################################################################
## Constants
readonly apiurl=https://192.168.51.81:8006/api2/json
## FIXME: There seems to be a problem with file upload where the task is
## registered to `node051` no matter what node we are actually uploading to? For
## now, let us just use `node051` everywhere.
readonly node=node051
################################################################################
## Parse arguments
username=
password=
vmids=
help () {
cat <<EOF
Usage: $0 [OPTION...] [ID...]
Authentication options:
--username STR Username, with provider (eg. niols@pve)
--password STR Password
If not provided via the command line, username and password will be looked for
in a '.proxmox' file in the current working directory, the username on the
first line, and the password on the second.
Others:
-h|-?|--help Show this help and exit
EOF
}
die () { printf "$@"; printf '\n'; help; exit 2; }
while [ $# -gt 0 ]; do
argument=$1
shift
case $argument in
--username) readonly username=$1; shift ;;
--password) readonly password=$1; shift ;;
-h|-\?|--help) help; exit 0 ;;
-*) die 'Unknown argument: `%s`.' "$argument" ;;
*) vmids="$vmids $argument" ;;
esac
done
if [ -z "$username" ] || [ -z "$password" ]; then
if [ -f .proxmox ]; then
{ read username; read password; } < .proxmox
else
die 'Required: `--username` and `--password`.\n'
fi
fi
################################################################################
## Getting started
from_response () { echo "$response" | jq -r "$1"; }
printf 'Authenticating...'
response=$(
http \
--verify no \
POST $apiurl/access/ticket \
"username=$username" \
"password=$password"
)
readonly csrfToken=$(from_response .data.CSRFPreventionToken)
readonly ticket=$(from_response .data.ticket)
printf ' done.\n'
proxmox () {
response=$(
http \
--verify no \
--form \
"$@" \
"Cookie:PVEAuthCookie=$ticket" \
"CSRFPreventionToken:$csrfToken"
)
}
wait_ () {
upid=$1
while :; do
proxmox GET $apiurl/nodes/$node/tasks/$upid/status
status=$(from_response .data.status)
case $status in
running) printf '.'; sleep 1 ;;
stopped) break ;;
*) printf ' unexpected status: `%s`\n' "$status"; exit 2 ;;
esac
done
}
################################################################################
## Stop VM
stop_vm () {
printf 'Stopping VM %d...' $1
proxmox POST $apiurl/nodes/$node/qemu/$1/status/stop \
'overrule-shutdown'==1
wait_ $(from_response .data)
printf ' done.\n'
}
################################################################################
## Delete VM
delete_vm () {
printf 'Deleting VM %d...' $1
proxmox DELETE $apiurl/nodes/$node/qemu/$1 \
'destroy-unreferenced-disks'==1 \
'purge'==1
wait_ $(from_response .data)
printf ' done.\n'
}
################################################################################
## Main loop
for vmid in $vmids; do
stop_vm $vmid
delete_vm $vmid
done