Install all the dependencies needed
ShellScript
sudo apt install -y qemu qemu-kvm libvirt-daemon libvirt-daemon-system virtinst libvirt-clients bridge-utils virt-manager cloud-image-utils libguestfs-tools
Reboot, that may work better.
Download an image, for example Ubuntu 20.04
ShellScript
# Ubuntu 20.04
wget https://cloud-images.ubuntu.com/releases/focal/release/ubuntu-20.04-server-cloudimg-amd64.img
# Ubuntu 22.04
wget https://cloud-images.ubuntu.com/releases/22.04/release/ubuntu-22.04-server-cloudimg-amd64.img
Create user data file so we can login after installation
ShellScript
cat >user-data.txt <<EOF
#cloud-config
hostname: bm1-vm00
system_info:
default_user:
name: root
home: /root
sudo: ALL=(ALL) NOPASSWD:ALL
password: secretpassword
chpasswd: { expire: False }
ssh_pwauth: True
EOF
Create a disk for cloud-init to utilize nocloud
ShellScript
USER_DATA_IMG=user-data.img
cloud-localds $USER_DATA_IMG user-data.txt
Create disk from image
ShellScript
DISK_SIZE=100G
QEMU_IMAGE=vm-disk-0.qcow2
qemu-img create -b ubuntu-20.04-server-cloudimg-amd64.img -F qcow2 -f qcow2 $QEMU_IMAGE $DISK_SIZE
If you run from root user
ShellScript
nano /etc/libvirt/qemu.conf
and uncomment user = "root"
and group = "root"
and run
ShellScript
service libvirtd restart
Install Virtual Machine
ShellScript
VM_NAME=vm-0
MEMORY_AMOUNT=4000000 # in MiB, that gives 4096 MB
VCPUS=4
virt-install --name $VM_NAME \
--virt-type kvm --memory $MEMORY_AMOUNT --vcpus $VCPUS \
--boot hd,menu=on \
--disk path=$QEMU_IMAGE,device=disk \
--disk path=$USER_DATA_IMG,format=raw \
--graphics none \
--os-type Linux --os-variant ubuntu20.04
Useful virsh
commands
ShellScript
# List VMs
virsh list --all
# Edit VM configuration
virsh edit $VM_NAME
# Log into VM
virsh console $VM_NAME
# List networks
virsh net-list --all
# Start network
virsh net-start default
# Autostart network
virsh net-autostart default
# Autostart VM
virsh autostart $VM_NAME
# Shutdown VM
virsh shutdown $VM_NAME
# Force shutdown
virsh destroy $VM_NAME
# Remove VM
virsh undefine $VM_NAME
# Change password (VM has to be shutdown)
virt-customize -a $QEMU_IMAGE --root-password password:new_pwd --uninstall cloud-init
Also, it might be useful to make the VM restarting on crush. Edit on_crash
VM configuration part like this
XML
<on_crash>restart</on_crash>
Other useful commands
ShellScript
# Change root password
passwd root
Leave a Reply