This is the multi-page printable view of this section. .
Documentation
-
1: Getting Started
-
2: VM Definition (vms.csv)
-
3: VM Lifecycle
-
4: Base Images
-
5: Network
-
6: Data Disks
-
7: Snapshots
-
8: User Accounts
-
9: VM Console
-
10: Remote Desktop
-
11: Firewall
-
12: macOS VMs
-
13: macOS Base Image
Complete guide to defining and managing KVM virtual machines with Ansible and libvirt.
- Getting Started — Install dependencies and create your first VM
- VM Definition — Configure VMs in
vms.csv - VM Lifecycle — List, start, stop, restart and destroy VMs
- Base Images — Download Linux and Windows base images
- Network — Bridge networking, DHCP and static IP
- Data Disks — Attach, resize and hot-plug data disks
- Snapshots — Create, restore and delete snapshots
- User Accounts — Create SSH users with passwordless sudo
- VM Console — VNC/SPICE and serial console access
- Remote Desktop — RDP access for Windows VMs
- Firewall — Managed nftables firewall
- macOS VMs — Hackintosh guests with keyboard-free boot
- macOS Base Image — How the macOS base image was built
1 - Getting Started
Requirements
- Host OS: Debian 12 (Bookworm)
- Packages:
qemu-kvm,libvirt-daemon-system,libvirt-clients,ovmf,swtpm
Installation
Quick Start
Project Structure
Next Steps
- VM Definition - Configure VMs in vms.csv
- VM Lifecycle - Start, stop, restart, destroy VMs
- Snapshots - Create and restore VM snapshots
- User Accounts - Setup Linux user accounts
- Data Disks - Attach, resize, and mount data disks
- VM Console - Access VM console
- Remote Desktop - RDP access for Windows VMs
- Network - Network architecture and bridge configuration
- Base Images - Download Linux and Windows base images
2 - VM Definition (vms.csv)
VMs are defined in vms.csv file. Each row represents a VM with the following fields:
| Field | Description | Example |
|---|---|---|
name |
VM name | win11-dev |
host |
KVM host (inventory name) | local |
type |
OS type: windows / linux / macos |
windows |
memory_mb |
Memory in MB | 8192 |
vcpus |
CPU cores | 4 |
os |
OS variant | win11 |
disk_gb |
System disk size | 80 |
data_disk_gb |
Data disk size (0 for none) | 10 |
base_image |
Base qcow2 image path | /path/to/base.qcow2 |
bridge |
Network bridge | br0 |
mac |
MAC address | 52:54:00:xx:xx:xx |
firmware |
efi or empty (BIOS) |
efi |
autostart |
Auto-start on boot (default: false) |
true |
storage_dir |
VM storage path (optional, default: /var/lib/libvirt/images) |
/data/vms |
ip |
Static IP address (optional, empty = DHCP). Linux: applied via cloud-init at create; macOS: applied later via configure-macos-network.yaml, see macOS VMs |
192.168.1.100 |
netmask |
Subnet CIDR (optional, default: 22) |
24 |
gateway |
Default gateway (required if ip is set) |
192.168.1.1 |
dns |
DNS servers, comma-separated (required if ip is set) |
8.8.8.8,8.8.4.4 |
Example vms.csv
Key Points
- MAC addresses: Each VM needs a unique MAC address for stable DHCP leases
- Autostart: Only debian12-01 is configured with
autostart=true(starts on host boot) - Storage: VMs can use custom storage paths or default
/var/lib/libvirt/images - Static IP: Linux VMs via cloud-init; macOS VMs via
configure-macos-network.yamlover SSH (no cloud-init on macOS) — see macOS VMs - Idempotent: The
create-vmplaybook checks if VM exists before creating, safe to run multiple times
3 - VM Lifecycle
All playbooks are idempotent (safe to run multiple times).
List VMs
Output example:
Start VM
Stop VM
Uses virsh shutdown which sends ACPI shutdown signal. For Windows VMs with QEMU guest agent configured, this triggers a clean shutdown.
Restart VM
Destroy VM
Deletes: domain definition, disk images (qcow2), OVMF VARS, cloud-init ISO, TPM state.
Warning: This is destructive and irreversible. The confirm=true flag is required.
4 - Base Images
Linux Base Images
The Linux VMs use official cloud images pre-configured with cloud-init support.
Debian
Download the latest Debian 12 (Bookworm) image:
Alternative versions: Browse https://cloud.debian.org/images/cloud/ for bookworm, bullseye, trixie, etc.
Ubuntu
Download the latest Ubuntu 24.04 LTS (Noble) image:
Download the latest Ubuntu 26.04 LTS (Resolute) image:
Important: Ubuntu cloud images require the virtio network driver. The VM templates in this project already use virtio, so no additional configuration is needed.
Note: Always verify the downloaded image checksum against the official SHA256SUMS file to avoid corrupted images causing boot failures.
Alternative versions: Browse https://cloud-images.ubuntu.com/ for other Ubuntu releases.
Fedora
Download the latest Fedora 44 Cloud Base image:
Note: Fedora uses wheel group for sudo privileges (not sudo). The setup-user playbook automatically detects this and uses the correct group.
Alternative versions: Browse https://fedoraproject.org/cloud/download/ for other Fedora releases.
Rocky Linux
Download the latest Rocky Linux 10 Cloud Base image:
Note: Rocky Linux uses wheel group for sudo privileges (same as RHEL/CentOS). The setup-user playbook automatically detects this and uses the correct group.
Alternative versions: Browse https://rockylinux.org/download for other Rocky Linux releases.
Configuration
Set the image path in vms.csv base_image field:
The image is automatically configured via cloud-init on first boot (SSH keys, user, packages, etc. from group_vars/kvm_hosts/vms_all.yaml).
Windows Base Image
The Windows qcow2 base image is built with packer-windows-kubevirt. It uses Packer + QEMU to produce a sysprep-generalized Windows image with:
- virtio drivers pre-installed (vioscsi, viostor, netkvm, vioserial, viorng, balloon, viofs)
- QEMU Guest Agent + Cloudbase-Init
- WinRM HTTPS (port 5986) + RDP (port 3389) enabled
- EFI boot with secure boot keys
Build your own custom image:
Then set the output path in vms.csv base_image field.
Windows VM Features
When type=windows, the domain XML template includes:
- Hyper-V enlightenments (relaxed, vapic, spinlocks, synic, stimer, etc.) for nested WSL2
- VMX passthrough for nested virtualization (WSL2/Hyper-V inside guest)
- EFI + vTPM 2.0 (OVMF secure boot + emulated TPM)
- virtio-scsi disk bus + virtio NIC
- Localtime clock with hypervclock
macOS Base Image
macOS guests use a self-contained qcow2 base image built by hand on the KVM host with OSX-KVM. Unlike the Linux and Windows images, it is neither downloaded nor built with Packer:
- macOS Sonoma 14.8.9 (x86_64), 4 vCPU / 8 GB, account
admin/admin, Remote Login enabled - OpenCore boot disk + blessed OVMF NVRAM template for keyboard-free cold boot
- 64 GiB virtual size, ~29 GiB actual usage, no backing file — ready to be used as a backing image
Each macOS VM gets its own system-disk overlay backed by macos-sonoma-base.img, an OpenCore overlay and a per-VM copy of the blessed OVMF VARS file. Set the image path in the vms.csv base_image field.
The full build walkthrough (installer download, bless, NVRAM validation, image conversion) is in macOS Base Image.
5 - Network
VMs connect to the local network via a bridge (default br0). Two IP assignment modes are supported:
DHCP Mode (default)
When ip field is empty, VMs receive IP addresses from the LAN’s DHCP server — same subnet as the host.
Each VM is assigned a pinned MAC address in vms.csv, so its DHCP lease is stable. To look up a VM’s IP:
Or use the list-vms playbook which does this automatically.
Static IP Mode (Linux VMs)
For Linux VMs, you can configure static IP addresses by filling in the ip, netmask, gateway, and dns fields in vms.csv.
Example vms.csv configuration
Notes
- Static IP configuration only works for Linux VMs (cloud-init network-config)
- Windows VMs do not support static IP configuration through this method
- When
ipis empty or omitted, the VM will use DHCP (default behavior) - The IP address is permanent and persists across reboots
- Ensure the static IP is outside the DHCP pool to avoid conflicts
Generated network configuration
Cloud-init will generate a netplan configuration at /etc/netplan/50-cloud-init.yaml:
Verification
After VM creation, verify the static IP is active:
Bridge Configuration
The KVM host requires a network bridge (br0) so VMs can access the LAN directly. Pick the method matching the host’s network manager: nmcli if NetworkManager is active (most desktops), ifupdown for classic server configs. Check with systemctl is-active NetworkManager.
Method 1: nmcli (NetworkManager)
First find the current connection profile, its IP config, and the NIC to bridge:
Create the bridge carrying the same static IP (or use ipv4.method auto for DHCP on br0), then attach the NIC as a bridge port, then disable the old profile so it doesn’t reclaim the NIC:
Both connections persist across reboots. To roll back: nmcli connection up "<existing profile name>" and restore connection.autoconnect yes.
Method 2: ifupdown (/etc/network/interfaces)
/etc/network/interfaces example:
Replace eth0 with your actual NIC name (check with ip link). After editing:
Verify the bridge is up:
6 - Data Disks
macOS VMs: the playbooks in this document do not apply to macOS guests. macOS disks sit on q35’s built-in SATA controller (not hotpluggable, and no virtio-blk driver), and macOS guests have no Python for Ansible. The data disk is instead created automatically at VM-create time from the
data_disk_gbcolumn (see macOS VMs); each playbook detectstype=macosand aborts with adiskutilpointer.
Attach Data Disk
Reads data_disk_gb from vms.csv. The VM must have data_disk_gb > 0 defined in CSV. Hot-plugs the disk to the running VM using virsh attach-disk --config --live (persistent + immediate effect).
Inside the VM, format and mount the new disk:
Resize Data Disk
Reads target data_disk_gb from vms.csv. The playbook will:
- Check if target size is larger than current (shrinking not supported)
- If VM is running → graceful shutdown and wait for stop
- Resize qcow2 file with
qemu-img resize - If VM was running → automatically start VM again
After resize, expand the filesystem inside the VM:
Note: If VM is already shut off, the playbook resizes the disk directly without auto-starting it.
Mount Disk
Format and mount data disk inside Linux VM. Requires the VM to be defined in hosts.ini.
Parameters
disk_device: disk device path (default:/dev/vdb)mount_point: mount point (required, e.g./data)disk_format: filesystem type (default:ext4)need_partition: create GPT partition (default:false, raw disk mount)format_force: force reformat (default:false)auto_mount: add to fstab (default:true)
Examples
The playbook will:
- Install
partedif needed - Create GPT partition table (if
need_partition=true) - Format disk with specified filesystem
- Add fstab entry with UUID
- Mount and verify
Tags: -t partition, -t format, -t mount (run specific steps only)
Extra Disks (add / list / delete)
Add as many extra virtio-blk disks as needed at runtime, independent of the
data_disk_gb column (which stays reserved for the single disk
create-vm.yaml builds). Disks are named <vm>-extra<N>.qcow2 in the VM’s
storage dir; both the next free index and the next free host target (vdX)
are auto-detected from live and persistent config, so repeated runs never
collide.
Linux guests only: virtio-blk hot-plug works on a running VM
(--config --live, visible immediately, no reboot); a shut-off VM gets
the disk via --config only, visible on next boot.
Add
List
Shows each disk’s index, virtual size, and its target in the live domain and/or persistent config:
Delete
Detaches the disk (live + config on a running VM — virtio-blk hot-unplug)
and deletes the qcow2 file. Destroys data, so confirm=true is required:
Identifying a disk inside the guest
The guest kernel assigns its own vdX names, which usually differ from the
host target. Each extra disk carries a serial <vm>-extra<N> — match on it:
Format/mount afterwards with mount-disk.yaml (pass the guest device
name, e.g. -e disk_device=/dev/vdc).
7 - Snapshots
Create, list, restore, and delete VM snapshots using libvirt’s built-in snapshot support.
Usage
Parameters
vm_name: VM name (required)snap_action:create/list/restore/delete(required)snapshot_name: snapshot name (auto-generated for create; required for restore/delete)snapshot_desc: description (optional, create only)halt: shutdown VM before snapshot for disk consistency, then restore to previous state (optional, create only, default:true)confirm: safety flag (required for restore and delete)
Behavior
- halt=true (default): If VM is running → shutdown → snapshot → start (restore running state). If VM is off → snapshot → remain off (preserve off state).
- halt=false: Create snapshot while VM is running (live snapshot). Faster but may have incomplete disk writes.
- Restore returns the VM to the exact state at snapshot time (running or off depending on snapshot state).
8 - User Accounts
Create user account on Linux VMs with SSH key and passwordless sudo. Auto-skips non-Linux hosts.
Usage
Parameters
HOSTS: target host or group (default:vms)username: user name to create (default:admin)ssh_pubkey: SSH public key file path (default:~/.ssh/id_rsa.pub)user_shell: login shell (default:/bin/bash)user_groups: user groups, comma-separated (auto-detected:wheelfor Fedora/RHEL,sudofor Debian/Ubuntu)passwordless_sudo: enable passwordless sudo (default:true)
Behavior
- Auto-detects OS via
gather_facts: true - Linux hosts: creates user, configures SSH key, enables passwordless sudo
- Non-Linux hosts (Windows, etc.): skipped with message showing detected OS
- Idempotent: safe to run multiple times on same host
9 - VM Console
VMs use different graphics backends based on OS type:
- Windows VMs: SPICE graphics (port 5900+)
- Linux VMs: VNC graphics (port 5900+)
Connect to VM console
Remote access via SSH tunnel
Example
View Windows VM boot process:
10 - Remote Desktop
Windows VMs support RDP (Remote Desktop Protocol) on port 3389.
Find VM IP address
Connect via RDP
Linux desktop (recommended): Remmina
Install: sudo apt install remmina remmina-plugin-rdp
GUI: supports RDP, VNC, SPICE, SSH Features: clipboard sharing, folder redirection, multi-monitor
Other options
- xfreerdp:
xfreerdp /v:<vm-ip> /u:Administrator - Windows: built-in “Remote Desktop Connection” (mstsc.exe)
- macOS: “Microsoft Remote Desktop” from App Store
Example
11 - Firewall
The nftables role manages the KVM host firewall. It supports Debian-family hosts (Debian, Ubuntu) and RedHat-family hosts (Fedora, Rocky Linux).
On Ubuntu, ufw is installed and enabled on some images; it is disabled by default (nftables_disable_ufw) so the two managers do not fight over the ruleset. On Fedora and Rocky, firewalld is stopped and masked by default (nftables_disable_firewalld) for the same reason.
Usage
nftables_ssh_sourcesmust contain at least one entry unlessnftables_ssh_allow_allis true, and should include the Ansible control node. The role refuses to apply an empty list otherwise. Existing SSH sessions survive the reload (established/related is accepted), but new ones are dropped unless the source is listed.
What the role does
- Validates inputs before touching the host (OS family, IPv4/CIDR format of
nftables_ssh_sources, non-empty SSH ports, set names). - Installs nftables (apt on Debian family, dnf on RedHat family); on Debian family, removes netfilter-persistent / iptables-persistent by default.
- Disables conflicting managers:
ufw --force disableon Ubuntu (when active); stops and masks firewalld on Fedora/Rocky. - Renders the ruleset to
/etc/nftables.conf(Debian family) or/etc/sysconfig/nftables.conf(RedHat family), validated withnft -c -fbefore writing; reloads vianft -fwhen the content changes. - Enables the nftables service at boot.
The rendered config defines two independent tables, inet _filter and inet _nat, deleting and recreating only these on reload — unrelated tables (for example Docker’s) are left untouched.
Variables
| Variable | Description | Default |
|---|---|---|
nftables_ssh_sources |
Source IPv4 addresses/CIDRs allowed to establish SSH | — (required unless allow-all) |
nftables_ssh_allow_all |
Accept SSH from any source | false |
nftables_ssh_ports |
Host SSH port list; list every port sshd listens on | [22] |
nftables_sets |
Named address sets (name + subnet list) |
[] |
nftables_rules |
Rules inserted verbatim into filter_default, filter_forward, nat_prerouting, nat_postrouting |
[] |
filter_forward_default_policy |
FORWARD chain default policy | drop |
net_postrouting_default_policy |
POSTROUTING chain default policy | accept |
nftables_remove_iptables_persistent |
Remove netfilter-persistent / iptables-persistent | true |
nftables_disable_ufw |
Disable ufw when installed and active | true |
nftables_disable_firewalld |
Stop and mask firewalld on RedHat family when installed | true |
Example
Built-in chains
deny— dropnolimit— acceptswitch— kill switch; point rules at it to toggle:
Notes
- With
nftables_setsandnftables_rulesempty, only loopback, established/related traffic, DHCP replies, ICMP and SSH fromnftables_ssh_sourcesare accepted. - The role replaces the distro-shipped
/etc/nftables.confwith its own template. On a host that was already running the distro config, the leftover emptyinet filtertable is removed only when it provably cannot filter traffic (no rules, no drop/reject policies). - On Fedora and Rocky,
nftables.service’sExecReloadbegins withflush ruleset, which would wipe foreign tables. The role therefore reloads by runningnft -f <config>directly instead ofsystemctl reload nftables. - Masking firewalld also blocks D-Bus activation, so
firewall-cmdcannot bring it back. Restore withsystemctl unmask firewalld.
12 - macOS VMs
macOS guests run alongside Linux/Windows VMs. See macOS Base Image for how the base image was built from scratch with kholia/OSX-KVM.
How macOS differs from Linux/Windows
| Aspect | Linux/Windows | macOS |
|---|---|---|
| Video | qxl/virtio/spice | vmware-svga via qemu:commandline |
| SMC | — | isa-applesmc,osk=... via qemu:commandline |
| Boot | system disk directly | OpenCore overlay (order 1) → macOS disk (order 2) |
| Firmware | distro OVMF or SeaBIOS | persistent OVMF + a pre-blessed NVRAM template |
| Network | libvirt <interface> |
bridge, virtio NIC pinned to root-bus slot=0x05 |
| IP config | cloud-init | no cloud-init — DHCP by default |
| Shutdown | virsh shutdown (ACPI) |
macOS ignores ACPI — shut down from the desktop or via SSH |
Assets
Shared read-only templates live in macos_asset_dir (default
/home/fish/bucket/kvm/macos/):
| File | Purpose |
|---|---|
macos-sonoma-base.img |
Sonoma 14.8.9 base image, admin/admin, Remote Login enabled |
OpenCore.qcow2 |
OpenCore boot disk (SIP disabled, auto-boot) |
OVMF_VARS-blessed.fd |
Pre-blessed NVRAM template — what makes keyboard-free cold boot possible |
Copying assets to another host
The three files are self-contained — copy them into the new host’s
macos_asset_dir and macOS VMs can be created there. The blessed Preboot
volume UUID, APFS layout and boot.efi path all travel with the files.
The new host additionally needs:
apt install ovmf— the template also references the host’s/usr/share/OVMF/OVMF_CODE_4M.fd(the persistent distro build). Do not use OSX-KVM’s bundled non-persistent copy, or the bless is invisible and cold boot stops at Apple’s disk picker (see Constraint 1 below)- Matching topology — q35 + built-in SATA at
1f:2+ system disk on port 2 are hardcoded indomain-macos.xml.j2, so using the same ansible-vms role satisfies this automatically - QEMU >= 8.2.2 and a similar libvirt version (for
qemu:commandline)
No need to copy: BaseSystem.img, fetch-macOS-v2.py,
boot-macos-install.sh — only used when re-creating the base image.
Configure (vms.csv)
Add a row with type=macos. disk_gb must equal the base image’s virtual
size (64). macOS uses DHCP, so leave ip/netmask/gateway/dns empty (set
them only if you want a static IP — see Static IP). The VNC port is
auto-assigned by libvirt (list-vms shows the actual port).
Data disk: set the data_disk_gb column (8th) to a size > 0 to attach an
extra SATA disk (sdc) on the same built-in AHCI controller — macOS sees it
natively, no kext needed. Like Linux/Windows guests, the SATA bus can not
be hotplugged, so set it at create time (or cold-attach + reboot); the
column is ignored on an already-created VM.
Create
Builds the two overlays (system disk + OpenCore), seeds the per-VM NVRAM from the blessed template, and defines/starts the domain. Cold boot needs zero keyboard input; the login window appears in ~40s.
Network: DHCP by default (upstream router on br0). Look up the IP with:
The IP column lists every VM’s address (e.g. 192.168.100.45 for macOS),
and the VNC column shows 127.0.0.1:<port>.
Ansible against macOS guests must use
-m raw— the guest has no Python interpreter.
Static IP (optional)
To switch a macOS VM from DHCP to a custom static IP, do it in two steps:
-
Define the network in
vms.csvfirst — fill theip,netmask(CIDR prefix, e.g.22),gatewayanddnscolumns (all four are required;configure-macos-network.yamlasserts this before touching the guest): -
Run the playbook against the current (DHCP) address:
boot_ipis the DHCP address the VM answers on right now (find it withlist-vms). The playbook logs in over SSH, locates the BSD interface by the VM’s MAC, appliesnetworksetup -setmanual/-setdnsservers, and verifies the new static IP answers on port 22. After that, update (or add) the VM’s entry inhosts.iniwith the static IP.
Start
Stop
macOS ignores ACPI shutdown, so the playbook only prints a notice:
- from the desktop: Apple menu → Shut Down
- or via SSH:
ssh admin@<ip> 'sudo shutdown -h now'
virsh shutdownis a no-op on macOS guests — do not use it.
Destroy
Stop the VM first (see above). The shared base image and assets are never touched.
Snapshots
macOS domains boot via pflash OVMF with a RAW NVRAM file, so libvirt refuses full (memory-included) snapshots. The snapshot playbook automatically falls back to disk-only snapshots for macOS:
Limitations to know:
- NVRAM is not part of the snapshot — boot state never reverts
- With
halt=truethe playbook aborts with a notice: macOS ignores ACPI, so shut it down yourself first (desktop or SSH) if you want a consistent snapshot - APFS on AHCI has no TRIM, so space reclaimed by deleting snapshots is limited
Template constraints (domain-macos.xml.j2)
Four details must match the validated hand-built config; each violation looks like a different, unrelated bug:
- Persistent OVMF: the host’s
/usr/share/OVMF/OVMF_CODE_4M.fd, not OSX-KVM’s non-persistent bundled build - Bless topology match: disks sit on q35’s built-in AHCI (PCI
1f:2); never add a secondich9-ahcidevice - NIC pinned to root-bus
slot=0x05: macOS’s virtio-net driver only binds at a fixed root-bus position — if libvirt auto-places the NIC on apcie-root-portchild, the guest never sees it <seclabel type='none'/>: an external (disk-only) snapshot nests the sharedOpenCore.qcow2/ base image one level deeper in the backing chain (… →.inited→ overlay → base). libvirt’svirt-aa-helperonly allows files named in the XML (source + one backingStore), so the deeper shared assets are AppArmor-denied and the VM won’t boot. Disabling per-domain AppArmor is safe here — theqemu:commandlinecustom devices already put this domain outside the standard confined-qemu model.
Full rationale and the bless procedure: macOS Base Image.
13 - macOS Base Image
On a Debian 12 KVM host, install macOS Sonoma by hand using the kholia/OSX-KVM approach, then freeze the resulting disk into a self-contained qcow2 template image for deriving macOS VMs.
- Output:
/home/fish/bucket/kvm/macos/macos-sonoma-base.img - Guest: macOS Sonoma 14.8.9 (x86_64), 4 vCPU / 8 GB, account
admin/admin, Remote Login enabled - OSX-KVM repo (hereafter “repo”):
/home/fish/bucket/OSX-KVM - Recorded: 2026-09-10 (updated 2026-09-20)
Prerequisites
- Host QEMU >= 8.2.2 (10.0.2 here), libvirt >= 9 (11.3.0 here, from bookworm-backports)
/dev/kvmavailable- OSX-KVM repo cloned to the repo path
- VNC client: a VNC viewer on the host’s
DISPLAY=:0, orssh -Lforwarding and connect locally - Disk space: the base image is ~29G actual; installation needs extra space
OVMF choice (important)
During installation you can use OSX-KVM’s bundled OVMF (non-persistent; does not affect the install):
OVMF_CODE_4M.fd(3.5M)OVMF_VARS-1920x1080.fd(128K) — must be the version without the-expsuffix
When blessing + integrating with libvirt you must switch to the host distro’s persistent OVMF:
- code:
/usr/share/OVMF/OVMF_CODE_4M.fd - vars: the 540672-byte persistent VARS file (copied from the VARS written to disk after a real bless)
OSX-KVM’s bundled OVMF is the RAM-backed / EmuVariable variant; it never reads or writes the on-disk VARS file. The
efi-boot-devicevariable written by bless cannot persist, and cold boot always stops at Apple Startup Manager.
1. Download and convert the installer media
2. Create the install directory and disk
qcow2 can be enlarged later:
qemu-img resize xxx.qcow2 128G+ inside the guestdiskutil apfs resizeContainer diskN 0. Starting small does not limit you.
3. Boot the install VM
Using the boot-macos-install.sh script (in /home/fish/bucket/OSX-KVM/):
Start it:
Key points:
- All three disks attach to q35’s built-in AHCI (
ide.0/ide.1/ide.2); do not add anich9-ahcidevice — this keeps the disk controller at PCI1f:2, which is the prerequisite for bless to land correctly (see “Technical background: PCI topology and bless”) snapshot=onprotects the OpenCore disk from modification during installationusb-tabletgives the VNC client absolute pointer positioning (clicks land accurately)- VNC display
:83(port 5983) - Uses the host’s persistent OVMF CODE (
/usr/share/OVMF/OVMF_CODE_4M.fd) so post-bless variables persist to disk
4. Complete the installation over VNC
Connect VNC:
Installation flow (fully manual clicking; prefer the mouse when the keyboard is unreliable):
- OpenCore picker: arrow-key to
macOS Base System, press Enter to enter Recovery - Recovery main window → double-click
Reinstall macOS Sonoma→ Continue (bottom right) - License page → Agree
- Target disk page: if only
macOS Base System(2.87G, the Recovery itself) is listed, the target disk is unpartitioned. Click Back to return to Recovery - Open Disk Utility → menu
View -> Show All Devices→ selectQEMU HARDDISK Media(the whole virtual disk) - Erase: Name
Macintosh HD/ FormatAPFS/ SchemeGUID Partition Map, then close Disk Utility - Enter Reinstall macOS Sonoma again;
Macintosh HDnow appears → Continue - Wait for the install (tens of minutes to an hour+); on
Restart→ click it - Back at the OpenCore picker → choose
Macintosh HD→ first-boot sequence - Setup Assistant:
- Language: English only (smaller language packs)
- Region: any (US/Australia are neutral; avoid odd timezones like American Samoa)
- Keyboard: default
- Migration: Not Now
- Do not install Xcode CLI tools (saves ~1.5G)
- Account: Full Name / Account Name
admin, passwordadmin
Pitfalls:
- On first boot the
vmware-svgadriver produces a grey screen for a few minutes — not a hang - Keyboard navigation in the Recovery main window is unreliable (Tab moves focus, but Space/Return won’t activate list items); list rows need a mouse double-click
- Scripted clicking over VNC (hand-written RFB PointerEvents) is unreliable on QEMU (BrokenPipe); a real VNC client is easiest
5. Size optimization (after install, before bless)
Via SSH or in Terminal:
6. Enable Remote Login (SSH)
System Settings → General → Sharing → Remote Login on; click the i on the
right → allow All users.
macOS has Remote Login off by default; disable the Network Firewall or allow ssh to avoid
kex_exchange_identification: Connection closed.
7. Bless + clean shutdown
This is the key step for keyboard-free cold boot (see “Technical background: PCI topology and bless”).
Inside the macOS guest:
Never hard-kill QEMU — the qcow2 gets dirty and may need journal recovery.
Wait for SSH to drop and the QEMU process to exit on its own (pgrep -f qemu-system returns nothing).
8. Verify and promote the NVRAM template
9. Produce the base image
Verify:
The result is a read-only template. Derive new VMs from it as backing:
Note: macOS APFS on AHCI SATA does not support TRIM (QEMU only supports it on virtio-blk/scsi/nvme), so
fstrimand sparse reclamation fromqemu-img convertare limited. A lean Sonoma install measures ~29G as the floor; it cannot be meaningfully reduced online.
Technical background: PCI topology and bless
This is the most common trap in macOS-on-KVM; understanding it avoids a lot of dead-end debugging.
The problem
Apple boot.efi draws its own Startup Manager (disk picker): if the
persisted efi-boot-device / efi-boot-device-data variables in OVMF are
missing, or the encoded device path does not match the current PCI topology,
it stops and waits for keyboard input.
And libvirt keyboard injection into macOS guests (send-key / QMP
input-send-event) was measured unresponsive across three USB controllers
(default xhci, xhci pinned to bus0, ich9-ehci1 + ich9-uhci1) — pixel-level
screenshot diff AE=0 — while the identical device config works under bare
qemu.
So the correct approach is to make cold boot itself require no keyboard input.
PCI topology matching
The q35 machine type ships with an ICH9 AHCI controller fixed at PCI
1f:2; libvirt’s <controller type='sata'> uses this built-in controller.
The -device ich9-ahci,id=sata in OSX-KVM’s tutorial scripts adds a
second controller at 02:0. A bless under the 02:0 topology produces an
efi-boot-device device-path that does not match inside a libvirt domain on
1f:2 — the picker appears again.
This topology mismatch was once misdiagnosed as “libvirt’s keyboard is broken, blocking integration”; the root cause was always just the device path mismatch.
The correct approach
The install script (boot-macos-install.sh) adds no extra ich9-ahci; disks
attach directly to q35’s built-in AHCI bus (ide.0 / ide.1 / ide.2),
naturally at 1f:2. Bless in this topology writes a device path of
PCI(dev=1f:2)/SATA(port=N)/..., which matches any libvirt domain also using
1f:2.
OpenCore config.plist notes
The NVRAM > Delete list must not contain efi-boot-device /
efi-boot-device-data (keep only boot-args and
ForceDisplayRotationInEFI), otherwise every boot erases them and breaks
bless persistence.
libvirt EFI domain lifecycle pitfall
virsh undefine on a domain with nvram requires --nvram, and that
deletes the VARS file. Because this VARS is a pre-baked template (not
libvirt’s auto-generated blank one), you must re-cp OVMF_VARS-blessed.fd
to the target path before manually re-defining:
The create-vm role re-seeds the VARS on every creation, so the normal role
path is unaffected; only manual XML re-definition needs this ordering.
Technical background: key decisions
- Sonoma over the latest macOS: OSX-KVM’s combination of Intel emulation (Skylake-Client + OpenCore) + Sonoma is the most mature; Intel support narrows starting with Tahoe
- Keep
snapshot=onon OpenCore.qcow2: EFI disk changes never land, avoiding cross-boot pollution - Never share the OVMF_VARS .fd: each VM must get its own copy, or NVRAM conflicts arise
Appendix A: OpenCore boot disk
OpenCore/OpenCore.qcow2 is a pre-built OpenCore boot disk. Key settings:
- SIP disabled:
csr-active-configset to NVRAM Protections disabled - Auto-boot:
Misc > Bootskips the picker (auto-selects the macOS disk after bless) NVRAM > Deletelist: deletes onlyboot-argsandForceDisplayRotationInEFI, and must not deleteefi-boot-device/efi-boot-device-data
Attach at install time:
snapshot=on ensures install-time changes never land on the OpenCore disk,
keeping the boot disk clean.
Appendix B: OSX-KVM repo asset inventory
Repo: kholia/OSX-KVM
Local path: /home/fish/bucket/OSX-KVM
| File | Size | Purpose |
|---|---|---|
fetch-macOS-v2.py |
– | Download macOS recovery images from Apple’s CDN (interactive version pick) |
BaseSystem.dmg |
753M | Original Apple recovery image download |
BaseSystem.img |
3.0G | Raw installer after dmg2img, attached directly to the VM |
OpenCore/OpenCore.qcow2 |
– | Patched OpenCore boot disk (SIP disabled, auto-boot) |
OVMF_CODE_4M.fd |
3.5M | OSX-KVM’s bundled OVMF CODE (non-persistent) |
OVMF_VARS-1920x1080.fd |
128K | OSX-KVM’s bundled OVMF VARS template (non-persistent) |
Repo scripts
| Script | Description |
|---|---|
boot-macos-install.sh |
Base image install boot script (step 3 above) |
boot-macos-ctrl4.sh |
Bless experiment script using q35’s built-in AHCI (1f:2), no extra ich9-ahci |
boot-macos-experiment.sh |
Early experimental install script (128G + extra ich9-ahci 02:0), reference only |
boot-macos-ctrl.sh / ctrl2 / ctrl3 |
Iterations, no longer needed |
boot-macOS-headless.sh |
OSX-KVM’s original GUI boot script |
Appendix C: Disk layout
Appendix D: Asset flow
Measured run log (2026-09-20, this build)
A full execution of the steps above, recording key commands and verification results for future reproduction.
Install-phase network pitfall and fix
The install VM uses QEMU user-net (slirp NAT); inside the guest
ipconfig getifaddr en0 returns 10.0.2.15 — a NAT-internal address the
host can neither ping nor SSH. Fix: add hostfwd=tcp::2222-:22 to the
-netdev user,id=net0 line of boot-macos-install.sh; the host then reaches
the guest via ssh -p 2222 admin@127.0.0.1, with no network topology change
and no manual typing in VNC.
Size optimization (step 5)
Bless verification (step 7)
Key output (confirming a UUID-addressed preboot volume and correct topology):
After shutdown (shutdown -h now; rc=255 is the normal SSH disconnect, not
an error), you must wait for the QEMU process to exit on its own on the
host (verify with pgrep/ps, not pgrep matching your own just-run shell
command), or the VARS file may not be fully flushed.
NVRAM verification (step 8)
Expect Boot0080, with devpath reading
PciRoot()/PCI(dev=1f:2)/SATA(port=2)/... — exactly what was measured this
run (port=2 corresponds to the install disk on ide.2, matching the
topology future libvirt domains use, see “Technical background: PCI topology
and bless”):
Producing the base image (step 9)
Final artifact verification:
Re-confirmed: shrinking the virtual disk from 128G to 64G kept the actual footprint at 29.1G (vs 28.9G measured for the earlier 128G virtual disk — essentially identical). This backs the conclusion stated at the top of this document: the base image cannot be shrunk by adjusting virtual disk size; 29G is the inherent floor for macOS APFS-on-AHCI without TRIM support (see the “Size optimization” and “Technical background” sections).