Skip to content

Instantly share code, notes, and snippets.

@mikejoh
Last active February 5, 2022 21:25
Show Gist options
  • Save mikejoh/c0c9be0275a1b4867c15994b52a98237 to your computer and use it in GitHub Desktop.
Save mikejoh/c0c9be0275a1b4867c15994b52a98237 to your computer and use it in GitHub Desktop.
KVM on Ubuntu 20.04 using (Ubuntu) cloud images

Running virtual machines on KVM and Ubuntu 20.04 using (Ubuntu) cloud images

  1. Check: egrep -c '(vmx|svm)' /proc/cpuinfo
  2. Check: sudo kvm-ok
  3. Install:
sudo apt update
sudo apt install qemu-kvm libvirt-daemon-system libvirt-clients bridge-utils virt-manager cloud-image-utils
  1. Add yourself to the libvirt and kvm groups:
sudo adduser $USER libvirt
sudo adduser $USER kvm
  1. Check: virsh list --all
  2. Check: sudo systemctl status libvirtd
  3. Export needed variables:
export MAC_ADDR=$(printf '52:54:00:%02x:%02x:%02x' $((RANDOM%256)) $((RANDOM%256)) $((RANDOM%256)))
export INTERFACE=eth001
export IP_ADDR=192.168.122.101
export VM_NAME=vm01
export UBUNTU_RELEASE=focal
export VM_IMAGE=$UBUNTU_RELEASE-server-cloudimg-amd64-disk-kvm.img
  1. Download the Ubuntu 20.04 cloud image:
wget https://cloud-images.ubuntu.com/$UBUNTU_RELEASE/current/$UBUNTU_RELEASE-server-cloudimg-amd64-disk-kvm.img
  1. Create a disk image:
qemu-img create -F qcow2 -b ./$VM_IMAGE -f qcow2 ./$VM_NAME.qcow2 10G
  1. Create cloud-init files:
cat >network-config <<EOF                                                             
ethernets:    
    $INTERFACE:
        addresses:
        - $IP_ADDR/24
        dhcp4: false
        gateway4: 192.168.122.1
        match:
            macaddress: $MAC_ADDR
        nameservers:
            addresses:
            - 1.1.1.1
            - 8.8.8.8
        set-name: $INTERFACE
version: 2
EOF

cat >user-data <<EOF
#cloud-config
hostname: $VM_NAME
manage_etc_hosts: true
users:
  - name: vmadm
    sudo: ALL=(ALL) NOPASSWD:ALL
    groups: users, admin
    home: /home/vmadm
    shell: /bin/bash
    lock_passwd: false
ssh_pwauth: true
disable_root: false
chpasswd:
  list: |
    vmadm:vmadm
  expire: false
EOF

touch meta-data
  1. Attach cloud-init to the image:
cloud-localds -v --network-config=network-config ./$VM_NAME-seed.qcow2 user-data meta-data
  1. Create the VM:
virt-install --connect qemu:///system \
  --virt-type kvm \
  --name $VM_NAME \
  --ram 1024 \ 
  --vcpus=2 \
  --os-type linux \
  --os-variant ubuntu20.04 \
  --disk path=$VM_NAME.qcow2,device=disk \
  --disk path=$VM_NAME-seed.qcow2,device=disk \
  --import \
  --network network=default,model=virtio,mac=$MAC_ADDR \
  --noautoconsole
  1. SSH to the VM or attach the console, use vmadm as username and password:
virsh console $VM_NAME
ssh vmadm@${IP_ADDRESS}
  1. Destroy the VM
virsh destroy $VM_NAME
virsh undefine $VM_NAME
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment