windows-builder

Build Windows images with Packer using WinRM communicator and PowerShell provisioners. Use when creating Windows AMIs, Azure images, or VMware templates.

npx skills add https://github.com/hashicorp/agent-skills --skill windows-builder

Windows Builder

Platform-agnostic patterns for building Windows images with Packer.

Reference: WinRM Communicator

Note: Windows builds incur significant costs and time. Expect 45-120 minutes per build due to Windows Updates. Failed builds may leave resources running - always verify cleanup.

WinRM Communicator Setup

Windows requires WinRM for Packer communication.

AWS Example

source "amazon-ebs" "windows" {
  region        = "us-west-2"
  instance_type = "t3.medium"

  source_ami_filter {
    filters = {
      name = "Windows_Server-2022-English-Full-Base-*"
    }
    most_recent = true
    owners      = ["amazon"]
  }

  ami_name = "windows-server-2022-${local.timestamp}"

  communicator   = "winrm"
  winrm_username = "Administrator"
  winrm_use_ssl  = true
  winrm_insecure = true
  winrm_timeout  = "15m"

  user_data_file = "scripts/setup-winrm.ps1"
}

WinRM Setup Script (scripts/setup-winrm.ps1)

<powershell>
# Configure WinRM
winrm quickconfig -q
winrm set winrm/config '@{MaxTimeoutms="1800000"}'
winrm set winrm/config/service '@{AllowUnencrypted="true"}'
winrm set winrm/config/service/auth '@{Basic="true"}'

# Configure firewall
netsh advfirewall firewall add rule name="WinRM 5985" protocol=TCP dir=in localport=5985 action=allow
netsh advfirewall firewall add rule name="WinRM 5986" protocol=TCP dir=in localport=5986 action=allow

# Restart WinRM
net stop winrm
net start winrm
</powershell>

Azure Example

source "azure-arm" "windows" {
  client_id       = var.client_id
  client_secret   = var.client_secret
  subscription_id = var.subscription_id
  tenant_id       = var.tenant_id

  managed_image_resource_group_name = "images-rg"
  managed_image_name                = "windows-${local.timestamp}"

  os_type         = "Windows"
  image_publisher = "MicrosoftWindowsServer"
  image_offer     = "WindowsServer"
  image_sku       = "2022-datacenter-g2"

  location = "East US"
  vm_size  = "Standard_D2s_v3"

  # Azure auto-configures WinRM
  communicator   = "winrm"
  winrm_use_ssl  = true
  winrm_insecure = true
  winrm_timeout  = "15m"
  winrm_username = "packer"
}

PowerShell Provisioners

Install Software

build {
  sources = ["source.amazon-ebs.windows"]

  # Install Chocolatey
  provisioner "powershell" {
    inline = [
      "Set-ExecutionPolicy Bypass -Scope Process -Force",
      "iex ((New-Object System.Net.WebClient).DownloadString('https://community.chocolatey.org/install.ps1'))"
    ]
  }

  # Install applications
  provisioner "powershell" {
    inline = [
      "choco install -y googlechrome",
      "choco install -y 7zip",
    ]
  }

  # Install IIS
  provisioner "powershell" {
    inline = [
      "Install-WindowsFeature -Name Web-Server -IncludeManagementTools"
    ]
  }
}

Windows Updates

provisioner "powershell" {
  inline = [
    "Install-PackageProvider -Name NuGet -Force",
    "Install-Module -Name PSWindowsUpdate -Force",
    "Import-Module PSWindowsUpdate",
    "Get-WindowsUpdate -Install -AcceptAll -AutoReboot",
  ]
  timeout = "2h"
}

# Wait for reboots
provisioner "windows-restart" {
  restart_timeout = "30m"
}

Cleanup

provisioner "powershell" {
  inline = [
    "# Clear temp files",
    "Remove-Item -Path 'C:\\Windows\\Temp\\*' -Recurse -Force -ErrorAction SilentlyContinue",
    "# Clear Windows Update cache",
    "Stop-Service -Name wuauserv -Force",
    "Remove-Item -Path 'C:\\Windows\\SoftwareDistribution\\*' -Recurse -Force -ErrorAction SilentlyContinue",
    "Start-Service -Name wuauserv",
  ]
}

Common Issues

WinRM Timeout

  • Increase winrm_timeout to 15m or more
  • Verify security group allows ports 5985/5986
  • Check user data script completed successfully

PowerShell Execution Policy

provisioner "powershell" {
  inline = [
    "Set-ExecutionPolicy Bypass -Scope Process -Force",
    "# Your commands here",
  ]
}

Long Build Times

  • Windows Updates can take 1-2 hours
  • Use pre-patched base images when available
  • Set provisioner timeout = "2h"

References

Mehr Skills von hashicorp

provider-actions
hashicorp
Implement Terraform Provider actions using the Plugin Framework. Use when developing imperative operations that execute at lifecycle events (before/after…
official
new-terraform-provider
hashicorp
Use this when scaffolding a new Terraform provider with the Plugin Framework: workspace layout, go module setup, provider server main.go, and a provider.go…
official
terraform-test
hashicorp
Comprehensive guide for writing and running Terraform tests. Use when creating test files (.tftest.hcl), writing test scenarios with run blocks, validating…
official
terraform-test
hashicorp
Umfassender Leitfaden zum Schreiben und Ausführen von Terraform-Tests mit Assertions, Mocking und Modulvalidierung. Schreiben Sie Testdateien mit der .tftest.hcl-Syntax und Run-Blöcken, die im Plan- oder Apply-Modus ausgeführt werden, und unterstützen sequenzielle und parallele Ausführung mit optionaler Zustandsisolation. Bedingungen für Ressourcenattribute, Ausgaben und Datenquellen prüfen; verwenden Sie expect_failures, um zu validieren, dass ungültige Eingaben ordnungsgemäß abgewiesen werden. Mock-Provider (Terraform 1.7.0+) simulieren Infrastrukturverhalten ohne...
official
provider-actions
hashicorp
Implementieren von imperativen Terraform-Provider-Aktionen bei Ressourcen-Lebenszyklus-Ereignissen unter Verwendung des Plugin-Frameworks. Unterstützt Vorher/Nachher-Erstellungs- und Vorher/Nachher-Aktualisierungs-Lebenszyklus-Trigger (Lösch-Ereignisse sind in Terraform 1.14.0 nicht verfügbar). Erfordert eine korrekte Schema-Definition mit den richtigen Framework-Typen, ElementType für Sammlungen und Validatoren für die Eingabevalidierung. Beinhaltet Fortschrittsberichterstattung, Timeout-Verwaltung und umfassende Fehlerbehandlung für langlaufende Operationen. Implementiert Polling und...
official
aws-ami-builder
hashicorp
Erstellt benutzerdefinierte Amazon Machine Images mit Packer's amazon-ebs Builder. Automatisiert die AMI-Erstellung aus Quell-AMIs mittels HCL-Vorlagen mit Provisionern zur Anpassung (Shell-Skripte, Datei-Uploads, Konfigurationsmanagement). Unterstützt Multi-Region-AMI-Verteilung über ami_regions und flexible Quell-AMI-Filterung nach Name, Besitzer und Virtualisierungstyp. Authentifiziert über Umgebungsvariablen, AWS-Anmeldedatei oder IAM-Instanzprofile; enthält Validierungs- und Build-Befehle für Vorlagen...
official
new-terraform-provider
hashicorp
Erstellt ein neues Terraform-Provider-Gerüst mit dem Plugin-Framework. Generiert einen neuen Go-Modul-Workspace mit der standardmäßigen "terraform-provider-"-Namenskonvention und initialisiert erforderliche Abhängigkeiten. Stellt eine Vorlage für die main.go-Datei bereit, die den HashiCorp-Plugin-Framework-Mustern folgt, mit TODO-Markierungen zur Anpassung. Validiert das Setup durch Ausführen von Build- und Testbefehlen, um sicherzustellen, dass der Provider kompiliert und erste Prüfungen besteht. Verwaltet den Workspace, indem die Absicht vor der Erstellung eines neuen... bestätigt wird.
official
azure-verified-modules
hashicorp
Zertifizierungsanforderungen und Best Practices für Azure Terraform-Module, die AVM-Konformität anstreben. Erzwingt Provider-Versionseinschränkungen (azurerm >= 4.0, < 5.0; azapi >= 2.0, < 3.0) und verbietet git-basierte Modulreferenzen zugunsten von festgelegten Terraform-Registry-Quellen. Schreibt Klein-Schlangenschreibweise für alle Bezeichner, präzise Variablentypen, diskrete Ausgabeattribute mittels Anti-Korruptionsschicht-Muster und alphabetisch geordnete Lokale vor. Erfordert Feature-Toggle-Variablen für neu hinzugefügte Ressourcen...
official