Skip to content

feat(image): spawn image import — Windows ISO→AMI via EC2 Image Builder (#83) - #90

Merged
scttfrdmn merged 16 commits into
mainfrom
feat/83-windows-ami-build
Jun 10, 2026
Merged

scttfrdmn merged 16 commits into
mainfrom
feat/83-windows-ami-build

Conversation

@scttfrdmn

@scttfrdmn scttfrdmn commented Jun 9, 2026 •

Copy link
Copy Markdown
Contributor

What

Adds a first-class spawn image import command that turns a Windows 11 ISO into
an AMI using AWS EC2 Image Builder's managed import-disk-image workflow
(shipped Jan 2025), then tags it for spawn launch --os windows.

This replaces the original hand-rolled qemu/Packer pipeline this branch
started as. That approach hit a wall: the Windows ISO's UEFI El Torito boot image
is the "Press any key to boot from CD" shim (unsatisfiable in a headless qemu
build — solved by remastering to efisys_noprompt.bin), after which WinPE
crash-looped under qemu (frozen on the firmware logo, zero disk writes). EC2
Image Builder does the entire conversion as a managed service — install,
drivers (ENA/NVMe/PCISerial/EC2WinUtil), EC2Launch v2, SSM agent, Defender, time
server, AMI registration — so none of that machinery is needed.

Changes

  • pkg/aws/imagebuilder.go — EnsureImageBuilderSLR,
    EnsureImportInfrastructure (idempotently provisions the instance-profile role
    • instance profile + infrastructure configuration; no CloudFormation needed),
      UploadISOToS3 (enforces the service's uppercase .ISO key), ImportWindowsISO,
      WaitForImage (polls GetImage to AVAILABLE/FAILED), TagAMIWindows.
  • cmd/image.go — spawn image parent + spawn image import child.
    --infra-config-arn optional (self-provisioned when omitted). -o json output.
  • Tests — flag-validation table test, upload-guard + ensureExists unit
    tests, ImportWindowsISO substrate smoke test.
  • Adds the imagebuilder aws-sdk-go-v2 dependency.
  • Rewrote infra/amis/windows/README.md around the Image Builder path.
  • Deleted the retired qemu/Packer files (windows11.pkr.hcl,
    Autounattend.xml, provision.ps1, import.sh, remaster-noprompt.sh) and
    the now-unused vmimport-role.yaml. Git history + the project memory note
    preserve the ISO no-prompt remaster insight.

Verification

  • go build ./..., make check (fmt/vet/golangci-lint + short tests) pass.
  • spawn image import --help renders; validation rejects missing --iso/--name.

Not done (follow-up)

A real end-to-end build needs a non-Evaluation Win11 Enterprise
23H2/24H2/25H2 ISO from the M365 admin center (import-disk-image rejects Eval,
and our on-hand ISO is Eval). Closing #83 is gated on that run.

Refs #83.

Closes #83.

scttfrdmn added 2 commits June 8, 2026 20:34
Self-service pipeline for turning a Windows ISO (e.g. Win11 25H2 Enterprise
Eval) into an EC2 AMI usable via `spawn launch --ami <id> --os windows`. A USER
runs this in their own account (the dev account, for us) — spore.host maintains
the templates; the build, AMI, and licensing are theirs.

infra/amis/windows/:
- README.md — the runbook: build-host options (Hyper-V primary / qemu fallback /
  EC2 metal for repeatability), prerequisites, build → export → import-image →
  tag → use from spawn, with the licensing/Dedicated-Host + vmimport caveats up
  front.
- windows11.pkr.hcl — Packer hyperv-iso builder (primary) + commented qemu
  fallback; boots the ISO with an Autounattend answer ISO, WinRM, provision,
  sysprep, export VHD.
- Autounattend.xml — unattended Win11 install (edition/partition/admin/WinRM +
  TPM/SecureBoot/RAM/CPU bypass for VM+EC2).
- provision.ps1 — installs the EC2 guest components import-image needs
  (EC2Launch v2, AWS PV/NVMe/ENA drivers, SSM agent, OpenSSH) then sysprep
  /generalize /shutdown. Deliberately does NOT bake spored — spawn installs it
  at launch (#77), keeping the AMI generic.
- import.sh — upload VHD to S3 + ec2 import-image + poll + tag spawn:os=windows.

deployment/cloudformation/vmimport-role.yaml — the fixed-name `vmimport` service
role import-image requires (AWS-documented trust + S3/EC2 policy).

Consumer side already shipped: `--os windows` flag + spawn:os tag handle an
imported AMI whose Platform metadata is unset, and spored installs at boot.

Validated: Autounattend.xml well-formed; import.sh shellcheck-clean;
vmimport-role.yaml passes cloudformation validate-template. packer validate +
provision.ps1 parse run on the (Windows) build host — deferred with the build.

Refs #83. Full end-to-end build is a multi-hour follow-up on a prepared host.
…te (#83)

The likely user flow is building locally with the ISO on their own machine, so
make qemu the active Packer builder (macOS/Linux) rather than a commented
fallback, with full brew prerequisites documented.

- README: macOS prereqs `brew install packer qemu xorriso awscli` with what each
  is for; explicit Apple-Silicon caveat (x86_64 ISO → qemu accel=tcg emulation,
  multi-hour install; Intel/Hyper-V/EC2-metal are ~30-60 min); answer-ISO build
  via xorriso (oscdimg is Windows-only); build invocation with iso_path/firmware
  vars.
- windows11.pkr.hcl: active qemu source (accel/firmware vars, IDE/e1000 for
  driverless Windows Setup, answer.iso as second CD); qemu emits qcow2 (the only
  format it allows) + a shell-local post-processor converts to stream-optimized
  VMDK for import-image. hyperv-iso kept as a documented commented alternative.
- import.sh: infer import Format from the disk extension (vmdk/vhd/vhdx/raw)
  instead of hardcoding vhd.

Now machine-validated locally: `packer validate` passes, import.sh
shellcheck-clean, Autounattend.xml well-formed, vmimport-role.yaml cfn-valid.
All brew prereqs installed on this host.

Refs #83.
@codecov

codecov Bot commented Jun 9, 2026 •

Copy link
Copy Markdown

scttfrdmn added 4 commits June 9, 2026 09:51
)

Real-build debugging surfaced three qemu issues, fixed here:
- qemuargs is a FULL override (per the qemu plugin docs) — the earlier
  single-drive qemuargs wiped Packer's default disk + install ISO + EFI pflash,
  leaving qemu with nothing to boot. Switched to cd_files (+ cd_label) so the
  Autounattend media attaches as a second CD without touching the defaults.
- UEFI via the plugin's efi_boot/efi_firmware_code/efi_firmware_vars (pflash),
  not -bios (which can't load the edk2 code blob); q35 machine type.
- boot_command: press Enter for "Press any key to boot from CD", with a
  UEFI-Interactive-Shell fallback (fs0:/fs1: → \EFI\BOOT\BOOTX64.EFI) for when
  the firmware drops to the shell instead of booting the DVD.

Verified the corrected qemu invocation includes all drives (disk + install ISO
+ answer CD + pflash pair). Apple-Silicon emulation is too slow/finicky for the
actual install; build runs on an x86 host (the README's qemu accel=kvm / metal
path).

Refs #83.
Capture the battle-tested runbook for building on a spawn-launched
c8i/m8i/r8i instance with --nested-virtualization (hardware-accelerated KVM,
~$0.70/hr, no metal needed; spawn#91). Real gotchas learned in practice:
- Use Ubuntu, NOT Amazon Linux 2023 — AL2023 repos ship only qemu-img, no full
  qemu-system. Ubuntu: apt install qemu-system-x86 ovmf xorriso.
- --volume-size lands as a SEPARATE unformatted disk on Ubuntu (root is its own
  8 GB device) — mkfs + mount it as the build workspace.
- Confirm /dev/kvm + vmx in the guest; add the user to the kvm group.
- Ubuntu OVMF is /usr/share/OVMF/OVMF_CODE_4M.fd + OVMF_VARS_4M.fd.
- rsync (not scp) for the multi-GB ISO so it resumes on a dropped connection.
- accel=kvm for a fast native build vs slow emulation.
Reordered "Where to build" to lead with nested-virt over metal.

Refs #83, spawn#91.
…er (#83)

The hardest part of the unattended Windows build was getting Setup to boot at
all. The stock ISO's UEFI El Torito boot image (efisys.bin) is the "Press any
key to boot from CD or DVD..." shim — it waits ~5s for a keypress, then gives
up. In a headless qemu/Packer build there's no reliable way to land a key in
that window: OVMF shows the prompt at a late, variable delay, and on miss the
firmware times the DVD out, burns minutes on PXE, and drops to the UEFI shell.
Verified repeatedly by screenshotting the VM's VNC framebuffer — the install
never started, the disk image never grew past 384 KB. boot_command keystroke
spam and a shell startup.nsh were both fragile or defeated by the shim.

Fix: remaster-noprompt.sh copies the ISO and dd's Microsoft's no-prompt boot
image (efi/microsoft/boot/efisys_noprompt.bin, shipped on the same media) over
the El Torito UEFI boot image in place — after verifying the target region is
exactly efisys.bin. Same size (1474560 B), so the UDF tree and the >4 GiB
install.wim stay bit-identical; only the boot image loses the prompt. The DVD
then boots Windows Setup directly, deterministically, with no keypress. (We
can't rebuild the ISO from files: this xorriso's mkisofs emulation has no UDF
write support and install.wim exceeds the 4 GiB ISO9660 limit.)

With the remastered ISO the qemu builder needs no boot_command at all; drop
startup.nsh and the keystroke logic. Healthy signal in VNC: "BdsDxe: starting
Boot0001 ... UEFI QEMU DVD-ROM" with no "Time out", qemu pinned >100% CPU.

README: new "The boot prompt" section + remaster step wired into the runbook.

Refs #83.
…#83)

Replace the hand-rolled qemu/Packer Windows-AMI pipeline with AWS's managed
EC2 Image Builder import-disk-image workflow (shipped Jan 2025), exposed as a
new first-class `spawn image import` command.

Why: the qemu/Packer path was a long fight — the Windows ISO's UEFI El Torito
boot image is the "Press any key to boot from CD" shim, which a headless qemu
build can't satisfy (solved by remastering the ISO to efisys_noprompt.bin), and
then WinPE crash-looped under qemu (frozen on the firmware logo, zero disk
writes). EC2 Image Builder does the whole conversion as a managed service —
runs the install, stages ENA/NVMe/PCISerial/EC2WinUtil drivers + EC2Launch v2 +
SSM agent + Defender, sets the time server, and registers the AMI — so none of
that machinery is needed.

New:
- pkg/aws/imagebuilder.go — Client methods: EnsureImageBuilderSLR,
  EnsureImportInfrastructure (idempotently creates the instance-profile role +
  instance profile + infrastructure configuration so no separate CloudFormation
  deploy is needed), UploadISOToS3 (enforces the service's uppercase .ISO key),
  ImportWindowsISO, WaitForImage (polls GetImage to AVAILABLE/FAILED),
  TagAMIWindows (spawn:os=windows).
- cmd/image.go — `spawn image` parent + `spawn image import` child. Flow: ensure
  SLR -> upload ISO if local -> ensure/É reuse infra -> import -> poll (progress)
  -> tag -> print AMI. --infra-config-arn is optional (self-provisioned when
  omitted). JSON output via -o json.
- Tests: validateImageImportFlags table test (cmd), upload-guard + ensureExists
  unit tests + an ImportWindowsISO substrate smoke test (pkg/aws).
- Adds the imagebuilder aws-sdk-go-v2 dependency.

Rewrote infra/amis/windows/README.md around the Image Builder path (supported
editions, BYOL, uppercase .ISO, us-east-1 vs NAT, troubleshooting via
CloudWatch). Deleted the retired qemu/Packer files (windows11.pkr.hcl,
Autounattend.xml, provision.ps1, import.sh, remaster-noprompt.sh) and the now
unused vmimport-role.yaml — git history + the project memory note preserve the
ISO no-prompt remaster insight for any future unsupported-edition path.

Note: import-disk-image requires a non-Evaluation Win11 Enterprise 23H2/24H2/25H2
ISO from the M365 admin center; a real end-to-end build is a follow-up once such
an ISO is available (our on-hand ISO is Evaluation).

Refs #83.
@scttfrdmn scttfrdmn changed the title docs(amis): Windows custom-AMI-from-ISO build templates + runbook (#83) feat(image): spawn image import — Windows ISO→AMI via EC2 Image Builder (#83) Jun 9, 2026
scttfrdmn added 9 commits June 9, 2026 16:47
Before spending a real (paid, ~30-min) Image Builder build, `spawn image verify
<iso>` reads the ISO's install.wim metadata locally — no mount, no external
tools, no AWS — and reports every edition with its image index, architecture and
build, then gives a clear ACCEPTED/REJECTED verdict for import-disk-image.

This caught two real cases in testing: a consumer Win11 Pro/Home ISO (rejected:
no Enterprise) and the Enterprise *Evaluation* ISO (rejected: Eval). The
business-editions ISO from the M365 admin center is correctly ACCEPTED and the
command tells you the exact --image-index (3 = Enterprise, 4 = Enterprise N).

- pkg/winiso: portable, dependency-free inspector. Streams the ISO, locates the
  WIM XML metadata blocks (UTF-16LE <WIM>…</WIM>), parses them with encoding/xml,
  dedupes by image index, ignores boot.wim WindowsPE images, and classifies each
  edition against the documented support matrix (Enterprise/Enterprise N, x64,
  non-Eval). Tail-first scan keeps it fast on multi-GB media. Hermetic tests
  cover business/Eval/consumer/arm64/WindowsPE/dedupe/no-WIM.
- cmd/image.go: `spawn image verify <iso>` (table or -o json); non-zero exit when
  unacceptable so scripts can gate on it.
- README: verify is now step 0 of the quick start; documents that Education/Pro
  are present-but-unsupported and that the M365 business ISO carries Enterprise
  at an index you pass via --image-index.

Refs #83.
Execute() already prints the error and exits non-zero, but rootCmd set neither
SilenceErrors nor SilenceUsage — so every command's runtime RunE failure printed
the error twice ("Error: ..." from cobra + the manual Fprintln) and dumped the
full usage wall for things like "file not found".

Set SilenceErrors + SilenceUsage on rootCmd (inherited by all subcommands). Now
a runtime error is a single clean line with no usage noise; `--help` and arg/flag
misuse messages are unaffected. Canonical cobra pairing with a manual print in
Execute().

Before:
  Error: open x.iso: no such file or directory
  Usage:
    spawn image verify <path-to.iso> [flags]
  ...12 lines of flags...
  open x.iso: no such file or directory      # printed again
After:
  open x.iso: no such file or directory
--bucket is now optional for a local ISO. When omitted, spawn uses (and creates
if needed) a managed, account+region-scoped bucket spawn-iso-import-<acct>-<region>
— matching the convention of spawn's other managed buckets (spawn-schedules-...).
The user no longer has to name or pre-create a bucket; `spawn image import --iso
./win11.iso --name win11` is fully self-contained.

Refs #83.
Two robustness/cost improvements found running the real import:

- Idempotent upload: UploadISOToS3 now HEADs the target key first and skips the
  upload when an object of the same byte size already exists. A failed import
  after a completed 8.5 GB upload no longer means re-uploading from scratch on
  retry.

- Auto-cleanup: after the AMI is built, the staged ISO is deleted (it's a
  transient artifact — the AMI is self-contained), and if spawn created the
  managed staging bucket, the now-empty bucket is removed too. New DeleteISOFromS3
  handles object + optional empty-bucket deletion. --keep-iso opts out. Cleanup
  is non-fatal (a leftover ISO is cost, not breakage) and only touches the object
  this run uploaded.

Refs #83.
Match the `spawn create-ami` convention: `spawn image import` is now async by
default — it starts the Image Builder build and returns the build ARN
immediately rather than blocking ~20-40 min.

- --wait blocks until the AMI is built (then tags it + cleans up the staged ISO).
  Bare --wait waits 60 min; --wait=N waits N minutes (NoOptDefVal).
- On wait timeout the build keeps running and the command exits NON-ZERO with a
  distinct error (WaitForImage returns aws.ErrWaitTimeout) — so scripts can tell
  "still building" apart from a build FAILURE or success. It also prints the
  async status/ARN so you can resume checking.
- New `spawn image status <build-arn>` (GetImageStatus): one-shot
  BUILDING/AVAILABLE/FAILED + the output AMI id once available.
- WaitForImage now takes an explicit timeout instead of a hardcoded 60m.

Tests: --wait flag parsing (async default 0, bare=60, =N). README documents the
async flow, status, and the timeout exit-code contract.

Refs #83.
…port tags (#83)

Real-run fixes and lifecycle gaps found running the clean import:

- SLR execution-role ARN: the default --execution-role passed the bare name
  "AWSServiceRoleForImageBuilder", which Image Builder resolves to
  role/AWSServiceRoleForImageBuilder — the WRONG ARN. The service-linked role
  actually lives at role/aws-service-role/imagebuilder.amazonaws.com/AWSServiceRoleForImageBuilder,
  so the build FAILED with "Unable to perform STS Assume role". EnsureImageBuilderSLR
  now returns the role's real ARN (creating it if needed, with a propagation
  wait), and import uses that ARN unless the user overrides --execution-role.

- `spawn ami delete <ami-id>`: deregister + delete backing EBS snapshots in one
  step, and if the AMI came from Image Builder (Ec2ImageBuilderArn tag, e.g.
  `spawn image import`), delete that image resource too. Confirmation prompt
  (--yes to skip). Fills the gap that forced manual aws ec2 deregister-image +
  delete-snapshot + imagebuilder delete-image for cleanup.

- Richer import tags: imported AMIs now also get spawn:source=iso-import and
  spawn:arch=x86_64 so they're discoverable/filterable via `spawn ami list`.

Refs #83.
Previously Ctrl-C during `spawn image import --wait` killed the process
ungracefully, leaving the build running in Image Builder with no pointer to it.
Now the wait phase runs under signal.NotifyContext (SIGINT/SIGTERM); an
interrupt is treated exactly like a --wait timeout: the build keeps running, we
print the build ARN + `spawn image status` (and the kept-ISO note), and exit
non-zero with a distinct, catchable error. WaitForImage already returns ctx.Err()
on cancellation, so this just classifies timeout-or-cancel as "detached, not
failed".

README notes the Ctrl-C/timeout detach behavior and the new ami list/delete.

Refs #83.
Make AMI deletion smart about shared snapshots, and expose snapshot info.

DeleteAMI:
- Retains snapshots that other AMIs still reference instead of deleting them
  (deleting a shared snapshot would break the other image). Per-snapshot
  decision is the pure snapshotDeletionDecision(): lookup-error → retain (safe),
  shared → retain, exclusive → delete.
- Aggregates per-snapshot + Image-Builder errors into DeleteAMIResult
  (DeletedSnapshots / RetainedSnapshots / SnapshotErrors / ImageBuilderError)
  instead of bailing on the first failure, so one stuck snapshot doesn't abort
  the rest. Deregister remains the single must-succeed step.
- The Image Builder DeleteImage call stays gated on the Ec2ImageBuilderArn tag,
  so deleting a NON-Image-Builder AMI never calls (or fails on) Image Builder —
  confirmed by TestDeleteAMI_NonImageBuilder_NoIBCall.

Visibility:
- `spawn ami list` gains a SNAPS column (backing-snapshot count).
- New `spawn ami snapshots <ami-id>`: lists each backing snapshot with size,
  state, encryption, age, and which OTHER AMIs share it ("exclusive" if none) —
  so it's clear what `ami delete` will keep vs remove.

Tests: pure table test for snapshotDeletionDecision (exclusive/shared/error),
substrate tests for not-found and the non-Image-Builder delete path. Full
shared-snapshot end-to-end coverage is blocked on substrate#322
(DescribeSnapshots + block-device-mapping.snapshot-id filter).

Refs #83, substrate#322.
The new top-level `image` command (spawn image import/verify/status) had no Tier 0
coverage decision, failing TestTier0_CommandCoverageGate. Defer it like `ami`:
the import path needs real EC2 Image Builder (Substrate can't emulate it), while
`image verify` is local and `pkg/winiso` is unit-tested.

Refs #83.
@scttfrdmn
scttfrdmn merged commit 9ea68b4 into main Jun 10, 2026
2 checks passed
@scttfrdmn
scttfrdmn deleted the feat/83-windows-ami-build branch June 10, 2026 04:36
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Build a Windows custom AMI from an ISO (Windows 11) and make it usable from spore.host tools

1 participant