Skip to content

Instantly share code, notes, and snippets.

@rimelek
Last active May 11, 2024 15:18
Show Gist options
  • Save rimelek/d448b76285a14c1c230e3684f728ed07 to your computer and use it in GitHub Desktop.
Save rimelek/d448b76285a14c1c230e3684f728ed07 to your computer and use it in GitHub Desktop.
Example script to start a simple Ubuntu VM from command line using libvirt
#!/usr/bin/env bash
# This script creates a and starts an Ubuntu VM
# requirements:
# - libvirt
# - vit-manager
set -eu -o pipefail
vm_name="libvirt-lan-test"
vm_hostname="$vm_name"
vm_root_pass="password"
vm_disk_dir="/mnt/data/libvirt-storage"
vm_disk_size="20G"
vm_disk_name="$vm_name"
vm_memory="2048" # in mebibytes
vm_vcpus="2"
vm_lan_bridge="br0"
vm_lan_mac="52:54:00:01:01:01"
ubuntu_codename="jammy"
ubuntu_arch="amd64"
force_download="false"
# do not modify
vm_disk_path="$vm_disk_dir/$vm_disk_name.qcow2"
vm_base_disk_remote_url="https://cloud-images.ubuntu.com/$ubuntu_codename/current/${ubuntu_codename}-server-cloudimg-${ubuntu_arch}-disk-kvm.img"
vm_base_disk_dir="$vm_disk_dir/base"
vm_base_disk_path="$vm_base_disk_dir/$ubuntu_codename.qcow2"
mkdir -p "$vm_disk_dir/base"
if [[ ! -f "$vm_base_disk_path" ]] || [[ "$force_download" == "true" ]]; then
curl -L "$vm_base_disk_remote_url" --output "$vm_base_disk_path"
fi
cp "$vm_base_disk_path" "$vm_disk_path"
vm_netplan_file="
network:
version: 2
renderer: networkd
ethernets:
lan:
dhcp4: true
link-local: []
match:
macaddress: $vm_lan_mac
"
virt-customize \
-a "$vm_disk_path" \
--root-password "password:$vm_root_pass" \
--run-command "dpkg-reconfigure -f noninteractive openssh-server" \
--upload <(echo "$vm_netplan_file"):/etc/netplan/main.yaml
virt-install \
--name "$vm_disk_name" \
--disk "path=$vm_disk_path,format=qcow2" \
--memory "$vm_memory" \
--os-variant="ubuntu${ubuntu_codename}" \
--vcpus "$vm_vcpus" \
--network "bridge=$vm_lan_bridge,model=virtio,mac=$vm_lan_mac" \
--graphics none \
--autoconsole none \
--import
echo "Run the following command to attach to the console of the VM:"
echo
echo "virsh console $vm_name"
echo
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment