qemu-system-x86 Creating an idempotent VM with SSH enabled via cloud-init and qemu monitor enabled over tcp
The above repo is the result of needing/wanting to be able to quickly bootstrap an Ubuntu VM in an idempotent way. This is especially useful for validating setups/bootstraps of lower level hardware , and not having to remember every time all the various (powerful) invocation options provided by Qemu.
What it does it leave you with a VM running, with SSH enabled/listening using public key authentication (password auth disabled). The disk is expanded by +5G to give you some scratch space, and each time the script is ran the entire setup is blown away (whilst being careful not to re-download an entire cloud-init image once again). To bootstrap ssh access and a valid system user, cloud-init is used- and a 'fake' metadata server runs using pythons built-in basic http server ( python3 -m http.server) all this is done for you automatically, however, and the script does some basic tests before running (e.g. do you have enough disk space? Is qemu installed? etc). It does assume you have python3 installed.
Running qemu in the background proved tricky (there's more to it than the argument -daemonize if you want to preserve the qemu monitor access (useful) and still have access to the serial output of the VM (useful)). The assumption here is you dont want/need a VGA display (hence -display none) and instead simply want a headless Ubuntu server VM without the hasstle/bloat of firing up VirtualBox, Parallels, VMware etc etc. A key benefit being you can run qemu-system-x86 'anywhere' such as locally, or in a CI/CD pipeline to verify a system or as part of a docs automation test to verify your docs work as documented (OpenZFS docs have a fabulous approach which does just that to test their docs with CI + qemu). Anyway, back to the script:
Once bootstrapped, the VM can be accessed from the host over ssh via:
ssh -p 2222 -i dummykey user1@127.0.0.1and the Qemu monitor can be accessed via:
nc 127.0.0.1 4444
QEMU 8.2.2 monitor - type 'help' for more information
(qemu)
The qemu script is commented throughout with links to various docs and bash-isms which may not be obvious how/why they work.
