Create a vm.zsh command

With subcommands to boot, reboot, or shutdown machines. Also, output in
color.

Signed-off-by: Anna Schumaker <Anna.Schumaker@Netapp.com>
This commit is contained in:
Anna Schumaker 2021-11-29 15:44:21 -05:00
parent 27245b3c70
commit b1fa0acd1f
2 changed files with 53 additions and 0 deletions

7
completions/_vm.zsh Normal file
View File

@ -0,0 +1,7 @@
#compdef vm.zsh
function _vm.zsh() {
_arguments \
'1:operation:(boot halt reboot shutdown start stop)' \
':virtual machine:($(virsh list --all --name))'
}

46
vm.zsh Executable file
View File

@ -0,0 +1,46 @@
#!/bin/zsh
autoload colors
colors
if [ "$#" -ne 2 ]; then
echo "Usage: $0 {boot,halt,reboot,shutdown,start,stop} {libvirt VM}"
exit 1
fi
function vm_boot() {
if virsh start $1 1>/dev/null 2>/dev/null; then
echo "$fg_bold[green]Starting VM: $fg_bold[white]$1$reset_color"
until nc -z -w 60 $1 22 2>/dev/null; do
sleep 1
done
fi
}
function vm_shutdown() {
if virsh shutdown $1 1>/dev/null 2>/dev/null; then
echo "$fg_bold[red]Stopping VM: $fg_bold[white]$1$reset_color"
while nc -z -w 60 $1 22 2>/dev/null; do
sleep 1
done
while virsh list --name | grep $1 >/dev/null; do
sleep 1
done
fi
}
machines=$(virsh list --all --name)
if [[ ${machines[(ie)$2]} -le ${#machines} ]]; then
case $1 in
"boot" | "start") vm_boot $2 ;;
"shutdown" | "stop" | "halt") vm_shutdown $2 ;;
"reboot")
vm_shutdown $2
sleep 1
vm_boot $2
;;
*)
echo "Boot, reboot, or shudown?"
exit 1
;;
esac
fi