2018年2月24日 星期六

Provision Ubuntu automatically with KVM and cloud-init


We usually want to prepare a fresh Ubuntu system to test our application or prepare a development environment. The following shows how to provision a fresh Ubuntu on your local machine by KVM virtualization technology.

Repository

https://github.com/tai271828/ubuntu-setup-automation

Pre-requirement

Ubuntu Xenial desktop

  • libvirt.pc (provided by libvirt-dev)
  • Python.h (provided by libpython3.5-dev)
  • cloud-localds (provided by cloud-image-utils)
  • optional: You may want to have virt-manager or virt-viewer in your system to see the provisioned system.

Setup


sudo apt-get install libvirt-dev
sudo apt-get install libpython3.5-dev
sudo apt-get install cloud-image-utils

virtualenv -p python3 venv

git clone https://github.com/tai271828/ubuntu-setup-automation.git

source venv/bin/activate

If you want to connect the KVM system later over SSH, you need to paste your public ssh key in this session (replace @@my_ssh_public_key@@ ). If you don't have a key or just want to use password to login, remove the whole session in order that cloud-init won't be confused by the invalid string @@my_ssh_public_key@@.

ssh_authorized_keys:
 - @@my_ssh_public_key@@

Run

In venv python virtual environment,

(venv) ubuntu-setup-automation/scripts⟫ cloud-localds /tmp/my-seed.img ../data/user-data && sudo cp /tmp/my-seed.img /var/lib/libvirt/images/ && sudo ./prepare-kvm-deployment && ../bin/create-instance-kvm


  • cloud-localds /tmp/my-seed.img ../data/user-data
    • This command prepares the image to inject user-data used by cloud-init later.
  • sudo cp /tmp/my-seed.img /var/lib/libvirt/images/
    • This command mv the user-data image, a.k.a my-seed.img, to the folder with libvirt accessible permission, so the user-data image could be used by qemu later.
  • sudo ./prepare-kvm-deployment && ../bin/create-instance-kvm
    • This command will
      • Fetch the official Ubuntu iso
      • Patch the iso so the iso has a preseed file to answer all questions prompted in the installation stage.
      • Initialize the fresh installed Ubuntu system by cloud-init.