Skip to content

Instantly share code, notes, and snippets.

@error10 error10/virt-helpers.sh
Last active Dec 4, 2015

Embed
What would you like to do?
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
You can’t perform that action at this time.