windows-vm: unattended provisioning and automation hooks

A Windows test VM was useless for automation because everything had to be done
through keystroke injection, which cannot reach a boot prompt and mangles
punctuation ('.' is key 'dot', not 'period').

Now an install ends with a machine that can be driven over the network:

  * provision.ps1 installs qemu-guest-agent, WinRM and OpenSSH Server, turns on
    auto-logon and disables sleep and lock, then writes C:\provision-done.txt
  * autounattend.xml is validated before every build - a missing wcm namespace
    makes Setup reject the file and reboot in a loop, which is exactly what cost
    an evening
  * build-answer-iso.sh refuses to build an answer file that would do that
  * win11.pkr.hcl now passes packer validate against proxmox 1.2.4: floppy_files
    and additional_arguments are not supported by the builder, so the answer file
    ships as a second CD and boot options moved into a boot_iso block

README rewritten around the two paths (template + clone, Packer rebuild) with the
four traps and the red herrings recorded.
This commit is contained in:
ziadarafat committed 2026-11-28 19:36:43 -07:00
1 parent 79125a841b
commit ef97badfb5
6 files changed
+246 -117

No files matched your search

+73 -60
View File
@@ -1,87 +1,100 @@
# Throwaway Windows VMs on Proxmox
Two ways to get a Windows guest for a test like "does this USB device work under
Windows", in the order they are worth using.
Goal: a Windows guest for testing things that need Windows (USB devices, firmware
tools, drivers) that can be **created and driven without touching the console**.
## 1. Template + clone (the everyday path)
## The automation hooks
One interactive install, then every later VM is a clone that boots in about a
minute.
A provisioned VM has everything needed to run it entirely over the network:
| Hook | What it gives you |
|---|---|
| `qemu-guest-agent` | `qm guest exec <id> -- cmd /c …`, `qm shutdown`, `qm guest cmd` — no RDP, no console |
| **OpenSSH Server** (port 22) | ordinary `ssh doge@<vm-ip>`, far easier to script than WinRM |
| **WinRM** (HTTP, Basic) | Packer's default communicator; `Invoke-Command` from PowerShell |
| **Auto-logon** | clones boot straight to a desktop; no sign-in screen to fight |
| Sleep and lock disabled | automation never races a screensaver or lock screen |
Credentials on a provisioned VM: `doge` / `doge123!` (thrown away with the VM).
`answer/autounattend.xml` creates the account and runs `provision.ps1` at first
logon, which installs all of the above. So an install ends with a usable,
remotely-driveable machine and no manual steps after the media prompt.
## 1. Template + clone (everyday path, ~1 minute)
```sh
# after the guest is installed and updated
qm start <id> # boot it, run Windows Update, then inside Windows:
# C:\Windows\System32\Sysprep\sysprep.exe /oobe /generalize /shutdown
qm template <id>
# every time after that
qm clone 9000 150 --name win-test --full
# once: build the baseline and convert it
qm clone 9000 150 --name win-test --full # 9000 = template id
qm set 150 --memory 8192 --cores 4
qm set 150 -hostpci0 0000:0c:00.3,pcie=1 # if the test needs USB hardware
qm set 150 -hostpci0 0000:0c:00.3,pcie=1 # only when the test needs real hardware
qm start 150
qm guest cmd 150 network-get-interfaces # find its address
ssh doge@<addr> # or: qm guest exec 150 -- cmd /c ver
```
A clone keeps the template's SID until sysprep strips it, which is why the
template is generalised rather than merely shut down.
Template creation: run `sysprep /oobe /generalize /shutdown` inside Windows, then
`qm template <id>`. Sysprep is optional for single-use test VMs — a clone without
it shares the SID, which only matters on a domain.
## 2. Packer rebuild (when you want a clean, reproducible image)
`win11.pkr.hcl` builds the template from the ISO with nobody watching. It exists
because the hand-driven install has one hostile step, described below.
## 2. Packer (clean rebuild from ISO)
```sh
packer init .
packer build -var proxmox_token="$PROXMOX_PACKER_TOKEN" win11.pkr.hcl
```
Needs `local:iso/win11-eval.iso` and `local:iso/virtio-win.iso`, and an API token
(user `packer@pve`, role with `VM.Allocate`, `VM.Config.*`, `Datastore.AllocateSpace`).
Keep the token in `secretctl`, never in this file.
Needs `local:iso/win11-eval.iso`, `local:iso/virtio-win.iso` and
`local:iso/answer.iso` (build the last one with `build-answer-iso.sh`). The token
belongs in `secretctl`, never here: create a `packer@pve` user with a role
carrying `VM.Allocate`, `VM.Config.*`, `Datastore.AllocateSpace`.
## The step that makes Windows installs awkward
## The traps (learned the hard way, 2026-11-28)
Windows installation media prints
1. **`qm reset` does not reload VM config.** Only `qm stop && qm start` applies
`qm set` changes. A reset reproduces the old behaviour exactly.
2. **An invalid `autounattend.xml` reboots Setup in a loop.** Missing the `wcm`
namespace (`xmlns:wcm="http://schemas.microsoft.com/WMIConfig/2002/State"`)
makes `wcm:action` an unbound prefix. Setup rejects the file at the first
screen: the purple installer window flashes, the screen goes black, UEFI
restarts. `build-answer-iso.sh` validates the XML before building.
3. **`qm sendkey` cannot satisfy the media boot prompt.** It injects PS/2 events,
a q35 VM has only a USB pointer, and the prompt lives ~5 s. It *does* work at
the firmware menu and inside Windows. Packer's `boot_command` repeats the
spacebar over VNC, which is the reliable way:
```hcl
boot_command = ["<wait><spacebar><wait><spacebar><wait><spacebar><wait>"]
```
QEMU key names matter when driving by hand: `.` is `dot`, `/` is `slash`,
`\` is `backslash`, `:` is `shift-semicolon`, space is `spc`.
4. **Pass the whole PCIe controller, not the device.** Device passthrough is
still enumerated by the host kernel first. Isolated on ziadpve:
`0c:00.3` (group 27), `0c:00.4` (28), `07:00.0` (22). `08:00.1`/`08:00.3`
share group 16 with a SATA controller and cannot be passed.
```
Press any key to boot from CD or DVD......
## Red herrings
- A **Proxmox logo with a progress bar** on a Windows VM's console is Proxmox's
own OVMF boot splash, not the Proxmox installer.
- `vfio-pci 0000:0c:00.3: resetting / reset done` per boot is normal.
- `ehci: PERIODIC list base register set …` is a cosmetic QEMU warning.
## Is it stuck or crashed?
```sh
printf 'screendump /tmp/f.ppm\n' | qm monitor <id>
pnmtopng /tmp/f.ppm > /tmp/f.png
md5sum /tmp/f.png # identical over time = static screen
```
for about five seconds. Miss it and the firmware falls through to the empty
disk and stops: `BdsDxe: No bootable option or device was found.`
`qm sendkey` is not a reliable way to satisfy it. It injects PS/2 keyboard
events, while a q35 VM has only a USB keyboard, and the event has to land inside
a five-second window. On 2026-11-28 that cost several failed boots: the keys
reached the *firmware boot menu* (which redrew) but never the media's prompt.
Packer's `boot_command` sends real keystrokes over VNC and lets you repeat them
across the whole window:
```hcl
boot_command = [
"<wait><spacebar><wait><spacebar><wait><spacebar><wait>",
]
```
That repetition is the fix — one press is a race, ten presses is not.
A crash loop shows repeated distinct frames; a waiting installer shows one stable
frame. Kill stray `screendump` loops or they pollute later comparisons.
## Files
| File | Purpose |
|---|---|
| `win11.pkr.hcl` | Packer build: VM, UEFI + vTPM, virtio disk/NIC, answer file, sysprep, template |
| `answer/autounattend.xml` | Unattended install: disk layout, local admin, auto-logon, OOBE skipped |
| `answer/firstboot.ps1` | First-logon hook: enable WinRM so Packer can drive the rest |
## Notes
- Deliver the answer file on a **floppy** (`floppy_files`), not a second CD-ROM:
Windows then finds it at `A:\` and there is no drive-letter guessing.
- `virtio-win` gives paravirtualised disk and network. Without it the guest runs
on emulated SATA and `e1000`, which is fine for a driver test but slow.
- `qemu_agent = true` means you can `qm shutdown`/`qm guest exec` later instead
of power-cycling or mounting the disk.
- For USB hardware tests, pass the whole PCIe controller (`hostpci0`) rather than
a single device: a device passthrough is still enumerated by the host kernel
first, so it inherits any host-side fault. Check the controller's IOMMU group
is alone before relying on it.
| `win11.pkr.hcl` | Packer build → UEFI + vTPM, virtio disk/NIC, answer ISO, sysprep, template |
| `answer/autounattend.xml` | Unattended install: disk, account, autologon, first-logon hook |
| `answer/provision.ps1` | Installs guest agent, WinRM, OpenSSH, auto-logon; writes `C:\provision-done.txt` |
| `build-answer-iso.sh` | Validates the answer file and builds `local:iso/answer.iso` |
+54 -31
View File
@@ -1,5 +1,23 @@
<?xml version="1.0" encoding="utf-8"?>
<unattend xmlns="urn:schemas-microsoft-com:unattend">
<!--
Unattended install for a Windows test VM on Proxmox.
Delivered on a floppy or a small ISO; Windows finds it at the root of the first
removable drive. Two things here are load-bearing:
* The wcm namespace. Without it this file is not well-formed XML, Setup rejects
it at the first screen and reboots in a loop - the purple screen that appears
for a second and vanishes is that failure, not a crash.
* FirstLogonCommands running provision.ps1, which turns on WinRM, OpenSSH and
the guest agent so the VM can be driven over the network instead of through
keystroke injection.
Validate before booting:
python3 -c "import xml.etree.ElementTree as ET; ET.parse('autounattend.xml')"
-->
<unattend xmlns="urn:schemas-microsoft-com:unattend"
xmlns:wcm="http://schemas.microsoft.com/WMIConfig/2002/State">
<settings pass="windowsPE">
<component name="Microsoft-Windows-International-Core-WinPE" processorArchitecture="amd64"
publicKeyToken="31bf3856ad364e35" language="neutral" versionScope="nonSxS">
@@ -9,10 +27,10 @@
<UILanguage>en-US</UILanguage>
<UserLocale>en-US</UserLocale>
</component>
<component name="Microsoft-Windows-Setup" processorArchitecture="amd64"
publicKeyToken="31bf3856ad364e35" language="neutral" versionScope="nonSxS">
<RunSynchronous>
<!-- Belt and braces: this VM has TPM + UEFI, but never let a check cost us the run. -->
<RunSynchronousCommand wcm:action="add">
<Order>1</Order>
<Path>reg add HKLM\SYSTEM\Setup\LabConfig /v BypassTPMCheck /t REG_DWORD /d 1 /f</Path>
@@ -21,52 +39,45 @@
<Order>2</Order>
<Path>reg add HKLM\SYSTEM\Setup\LabConfig /v BypassSecureBootCheck /t REG_DWORD /d 1 /f</Path>
</RunSynchronousCommand>
<RunSynchronousCommand wcm:action="add">
<Order>3</Order>
<Path>reg add HKLM\SYSTEM\Setup\LabConfig /v BypassRAMCheck /t REG_DWORD /d 1 /f</Path>
</RunSynchronousCommand>
<RunSynchronousCommand wcm:action="add">
<Order>4</Order>
<Path>reg add HKLM\SYSTEM\Setup\LabConfig /v BypassCPUCheck /t REG_DWORD /d 1 /f</Path>
</RunSynchronousCommand>
</RunSynchronous>
<DiskConfiguration>
<WillShowUI>OnError</WillShowUI>
<Disk wcm:action="add">
<DiskID>0</DiskID>
<WillWipeDisk>true</WillWipeDisk>
<CreatePartitions>
<CreatePartition wcm:action="add">
<Order>1</Order><Type>EFI</Type><Size>100</Size>
</CreatePartition>
<CreatePartition wcm:action="add">
<Order>2</Order><Type>MSR</Type><Size>16</Size>
</CreatePartition>
<CreatePartition wcm:action="add">
<Order>3</Order><Type>Primary</Type><Extend>true</Extend>
</CreatePartition>
<CreatePartition wcm:action="add"><Order>1</Order><Type>EFI</Type><Size>100</Size></CreatePartition>
<CreatePartition wcm:action="add"><Order>2</Order><Type>MSR</Type><Size>16</Size></CreatePartition>
<CreatePartition wcm:action="add"><Order>3</Order><Type>Primary</Type><Extend>true</Extend></CreatePartition>
</CreatePartitions>
<ModifyPartitions>
<ModifyPartition wcm:action="add">
<Order>1</Order><PartitionID>1</PartitionID><Format>FAT32</Format><Label>System</Label>
</ModifyPartition>
<ModifyPartition wcm:action="add">
<Order>2</Order><PartitionID>2</PartitionID>
</ModifyPartition>
<ModifyPartition wcm:action="add"><Order>2</Order><PartitionID>2</PartitionID></ModifyPartition>
<ModifyPartition wcm:action="add">
<Order>3</Order><PartitionID>3</PartitionID><Format>NTFS</Format><Label>Windows</Label><Letter>C</Letter>
</ModifyPartition>
</ModifyPartitions>
</Disk>
</DiskConfiguration>
<ImageInstall>
<OSImage>
<InstallFrom>
<MetaData wcm:action="add">
<Key>/IMAGE/INDEX</Key>
<Value>1</Value>
</MetaData>
</InstallFrom>
<InstallTo><DiskID>0</DiskID><PartitionID>3</PartitionID></InstallTo>
</OSImage>
</ImageInstall>
<UserData>
<AcceptEula>true</AcceptEula>
<FullName>kraken</FullName>
<FullName>doge</FullName>
<Organization>homelab</Organization>
</UserData>
</component>
@@ -78,6 +89,16 @@
<ComputerName>WINTEST</ComputerName>
<TimeZone>UTC</TimeZone>
</component>
<component name="Microsoft-Windows-Deployment" processorArchitecture="amd64"
publicKeyToken="31bf3856ad364e35" language="neutral" versionScope="nonSxS">
<RunSynchronous>
<RunSynchronousCommand wcm:action="add">
<Order>1</Order>
<Description>never lock, never sleep</Description>
<Path>cmd /c powercfg /change standby-timeout-ac 0 &amp; powercfg /change monitor-timeout-ac 0</Path>
</RunSynchronousCommand>
</RunSynchronous>
</component>
</settings>
<settings pass="oobeSystem">
@@ -89,29 +110,31 @@
<HideOnlineAccountScreens>true</HideOnlineAccountScreens>
<HideWirelessSetupInOOBE>true</HideWirelessSetupInOOBE>
<ProtectYourPC>3</ProtectYourPC>
<SkipMachineOOBE>true</SkipMachineOOBE>
<SkipUserOOBE>true</SkipUserOOBE>
</OOBE>
<UserAccounts>
<LocalAccounts>
<LocalAccount wcm:action="add">
<Name>kraken</Name>
<Name>doge</Name>
<DisplayName>doge</DisplayName>
<Group>Administrators</Group>
<Password><Value>kraken123!</Value><PlainText>true</PlainText></Password>
<Password>
<Value>doge123!</Value>
<PlainText>true</PlainText>
</Password>
</LocalAccount>
</LocalAccounts>
</UserAccounts>
<AutoLogon>
<Enabled>true</Enabled>
<Username>kraken</Username>
<Password><Value>kraken123!</Value><PlainText>true</PlainText></Password>
<Username>doge</Username>
<Password><Value>doge123!</Value><PlainText>true</PlainText></Password>
<LogonCount>999</LogonCount>
</AutoLogon>
<FirstLogonCommands>
<SynchronousCommand wcm:action="add">
<Order>1</Order>
<Description>collect USB report</Description>
<CommandLine>cmd /c if exist A:\firstboot.ps1 powershell.exe -ExecutionPolicy Bypass -NoProfile -File A:\firstboot.ps1</CommandLine>
<Description>provision automation hooks</Description>
<CommandLine>cmd /c for %i in (D E F G) do @if exist %i:\p.ps1 powershell.exe -ExecutionPolicy Bypass -NoProfile -File %i:\p.ps1</CommandLine>
</SynchronousCommand>
</FirstLogonCommands>
</component>
-16
View File
@@ -1,16 +0,0 @@
# Runs once on first logon in a freshly installed guest, before Packer's
# provisioners take over over WinRM. Keep it short: everything heavier is a
# Packer provisioner so it is visible in the build log.
$ErrorActionPreference = 'SilentlyContinue'
Set-Content -Path 'C:\firstboot.txt' -Value "firstboot $([DateTime]::UtcNow.ToString('s'))"
# WinRM is how Packer drives the rest of the build.
Enable-PSRemoting -Force -SkipNetworkProfileCheck
Set-Item WSMan:\localhost\Service\Auth\Basic -Value $true
Set-Service WinRM -StartupType Automatic
Start-Service WinRM
Set-NetFirewallRule -DisplayGroup 'Windows Remote Management' -Enabled True
# A test guest that sleeps, never hibernates, and has no lock screen.
powercfg /change standby-timeout-ac 0
powercfg /change monitor-timeout-ac 0
+70
View File
@@ -0,0 +1,70 @@
# One-shot provisioning for a Windows test VM.
#
# Run once from inside the guest (or from Packer). After this the machine can be
# driven entirely over the network, with no keystroke injection, which is the
# whole point: qm sendkey cannot reach a boot prompt and mangles punctuation.
#
# Installs:
# * virtio-win guest tools -> qemu-guest-agent (qm guest exec / qm shutdown)
# * WinRM over HTTP -> Packer communicator, Invoke-Command
# * OpenSSH Server -> ordinary ssh, which is far nicer to script
# * auto-logon for the test account, so clones land on a desktop unattended
$ErrorActionPreference = 'SilentlyContinue'
$log = 'C:\provision.log'
function Note($m) { "$([DateTime]::UtcNow.ToString('HH:mm:ss')) $m" | Add-Content $log }
Remove-Item $log -Force -ErrorAction SilentlyContinue
Note "provisioning $env:COMPUTERNAME"
# --- virtio-win guest tools (brings qemu-guest-agent and the paravirt drivers)
$virtio = Get-PSDrive -PSProvider FileSystem | Where-Object { Test-Path "$($_.Root)virtio-win-guest-tools.exe" } | Select-Object -First 1
if ($virtio) {
Note "installing virtio-win guest tools from $($virtio.Root)"
Start-Process "$($virtio.Root)virtio-win-guest-tools.exe" -ArgumentList '/S','/quiet','/norestart' -Wait
Note "virtio tools exit: $LASTEXITCODE"
} else {
Note "virtio-win ISO not attached, skipping guest tools"
}
# --- WinRM: Packer's default communicator
Enable-PSRemoting -Force -SkipNetworkProfileCheck
Set-Item WSMan:\localhost\Service\Auth\Basic -Value $true
Set-Item WSMan:\localhost\Service\AllowUnencrypted -Value $true
Set-Service WinRM -StartupType Automatic
Start-Service WinRM
Set-NetFirewallRule -DisplayGroup 'Windows Remote Management' -Enabled True
Note "winrm enabled"
# --- OpenSSH Server: much easier to script than WinRM from Linux
$cap = Get-WindowsCapability -Online -Name 'OpenSSH.Server*'
if ($cap.State -ne 'Installed') {
Note "installing OpenSSH server"
Add-WindowsCapability -Online -Name $cap.Name | Out-Null
}
Set-Service sshd -StartupType Automatic
Start-Service sshd
New-NetFirewallRule -Name 'sshd-in' -DisplayName 'OpenSSH Server' -Enabled True -Direction Inbound -Protocol TCP -LocalPort 22 -Action Allow | Out-Null
Note "sshd state: $((Get-Service sshd).Status)"
# --- keep it awake and never lock, so automation is not fighting a lock screen
powercfg /change standby-timeout-ac 0
powercfg /change monitor-timeout-ac 0
powercfg /setacvalueindex SCHEME_CURRENT SUB_NONE ConsoleLock 0
New-ItemProperty -Path 'HKLM:\SOFTWARE\Policies\Microsoft\Windows\Personalization' -Name NoLockScreen -Value 1 -PropertyType DWord -Force | Out-Null
New-ItemProperty -Path 'HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Winlogon' -Name AutoAdminLogon -Value '1' -PropertyType String -Force | Out-Null
# --- test account: known password, never expires
$user = 'doge'
$pass = 'doge123!'
if (Get-LocalUser -Name $user -ErrorAction SilentlyContinue) {
Set-LocalUser -Name $user -Password (ConvertTo-SecureString $pass -AsPlainText -Force) -PasswordNeverExpires $true
} else {
New-LocalUser -Name $user -Password (ConvertTo-SecureString $pass -AsPlainText -Force) -PasswordNeverExpires $true | Out-Null
Add-LocalGroupMember -Group Administrators -Member $user
}
Set-ItemProperty -Path 'HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Winlogon' -Name DefaultUserName -Value $user
Set-ItemProperty -Path 'HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Winlogon' -Name DefaultPassword -Value $pass
Note "autologon set for $user"
"COMPLETE" | Set-Content 'C:\provision-done.txt'
Note "done"
+34
View File
@@ -0,0 +1,34 @@
#!/bin/sh
# Builds local:iso/answer.iso from the answer files, and refuses to build an
# answer file Windows Setup would reject.
#
# Why the validation matters: a malformed autounattend.xml (for example, using
# wcm:action without the wcm namespace) makes Setup show the purple installer
# window for about a second, then reboot - in a loop, forever, with nothing in
# any log to explain it.
set -eu
here=$(cd "$(dirname "$0")" && pwd)
work=${WORK:-/tmp/answer-iso}
iso_out=${ISO_OUT:-/var/lib/vz/template/iso/answer.iso}
python3 - "$here/answer/autounattend.xml" <<'PY'
import sys, xml.etree.ElementTree as ET
path = sys.argv[1]
try:
ET.parse(path)
except ET.ParseError as e:
raise SystemExit("autounattend.xml is not valid XML (%s) - Setup would reboot in a loop" % e)
print("autounattend.xml: valid XML")
PY
rm -rf "$work"
mkdir -p "$work"
cp "$here/answer/autounattend.xml" "$work/autounattend.xml"
# Windows Setup needs the script beside the answer file, at a short name, because
# FirstLogonCommands searches drive letters for it.
cp "$here/answer/provision.ps1" "$work/p.ps1"
genisoimage -quiet -o "$work/answer.iso" -J -R -V ANSWER "$work/autounattend.xml" "$work/p.ps1"
install -m 0644 "$work/answer.iso" "$iso_out"
echo "wrote $iso_out ($(stat -c%s "$iso_out") bytes)"
+15 -10
View File
@@ -89,8 +89,10 @@ source "proxmox-iso" "win11" {
bridge = "vmbr0"
}
iso_file = var.iso_file
unmount_iso = true
boot_iso {
iso_file = var.iso_file
unmount = true
}
additional_iso_files {
device = "ide2"
iso_file = var.virtio_iso
@@ -98,12 +100,16 @@ source "proxmox-iso" "win11" {
iso_storage_pool = "local"
}
# The answer file rides on a floppy, so Windows Setup finds it at A:\ and it
# never collides with a CD-ROM drive letter.
floppy_files = [
"answer/autounattend.xml",
"answer/firstboot.ps1",
]
# The answer file ships as a small ISO rather than a floppy: the proxmox-iso
# builder has no floppy_files option. Build it with tools/windows-vm/build-answer-iso.sh,
# which also validates the XML first - an invalid answer file makes Setup
# reboot in a loop, which is a miserable thing to debug.
additional_iso_files {
device = "ide0"
iso_file = "local:iso/answer.iso"
unmount = true
iso_storage_pool = "local"
}
# This is the whole point of the exercise. Repeat the spacebar rather than
# pressing once: the prompt renders a variable beat after the DVD is selected.
@@ -126,8 +132,7 @@ source "proxmox-iso" "win11" {
# Convert the finished build into a template: it can only be cloned, never
# started by accident.
template_name = var.template_name
additional_arguments = "-device usb-kbd"
template_name = var.template_name
}
build {