Skip to content

Instantly share code, notes, and snippets.

@error10
Last active September 16, 2020 20:10
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save error10/90ba6944284d2980a41a to your computer and use it in GitHub Desktop.
Save error10/90ba6944284d2980a41a to your computer and use it in GitHub Desktop.
Bash helper functions for mangling libvirt virtual machines
#!/usr/bin/env bash
# Check whether a named virtual machine exists.
#
# Arguments:
# 1: virtual machine name given by virsh
#
# Returns:
# 0 if virtual machine exists
# 1 if virtual machine does not exist
vm_exists() {
virsh domstate $1 >/dev/null 2>&1
return $?
}
# Check whether a named virtual machine is running.
#
# Arguments:
# 1: virtual machine name given by virsh
#
# Returns:
# 0 if virtual machine is running
# 1 if virtual machine is not running or does not exist
vm_is_running() {
if [ "$(virsh domstate $1 2>/dev/null)" == "running" ]; then
return 0
else
return 1
fi
}
# Sleep until the given virtual machine is no longer running.
# Returns when the virtual machine is not running or does not exist.
#
# Arguments:
# 1: virtual machine name given by virsh
wait_for_vm_to_stop() {
while vm_is_running $1; do
sleep 1
done
}
# Shut down a virtual machine through the normal shutdown signal. This
# results in a clean shutdown via the guest operating system.
#
# Arguments:
# 1: virtual machine name given by virsh
shutdown_vm() {
if vm_is_running $1; then
virsh shutdown $1
fi
}
# Forcibly stop a virtual machine, even if it is not responding.
#
# Arguments:
# 1: virtual machine name given by virsh
force_stop_vm() {
if vm_is_running $1; then
virsh destroy $1
fi
}
# Delete a virtual machine, all of its metadata, snapshots and storage.
# This should remove all traces of the VM.
#
# Arguments:
# 1: virtual machine name given by virsh
delete_vm() {
force_stop_vm $1
virsh undefine $1 --managed-save --snapshots-metadata --nvram --remove-all-storage
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment