windows-builder

作成者: hashicorp

Packerを使用し、WinRM通信機能とPowerShellプロビジョナーでWindowsイメージを構築します。Windows AMI、Azureイメージ、VMwareテンプレートを作成する際に使用します。

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

hashicorpのその他のスキル

provider-actions
hashicorp
Plugin Frameworkを使用してTerraform Providerのアクションを実装します。ライフサイクルイベント(前/後…)で実行される命令的操作を開発する際に使用します。
official
new-terraform-provider
hashicorp
新しいTerraformプロバイダーをPlugin Frameworkでスキャフォールディングする際に使用します:ワークスペースレイアウト、goモジュールのセットアップ、プロバイダーサーバーのmain.go、およびprovider.go…
official
terraform-test
hashicorp
Terraformテストの作成と実行に関する包括的なガイド。テストファイル(.tftest.hcl)の作成、runブロックを使ったテストシナリオの記述、検証の際に使用します…
official
terraform-test
hashicorp
Terraformテストの作成と実行に関する包括的なガイド。アサーション、モック、モジュール検証を含む。.tftest.hcl構文を使用してテストファイルを作成し、planまたはapplyモードで実行されるrunブロックを記述。逐次実行と並列実行をサポートし、オプションで状態の分離も可能。リソース属性、出力、データソースに対する条件をアサートし、expect_failuresを使用して無効な入力が適切に拒否されることを検証。モックプロバイダー(Terraform 1.7.0以降)はインフラストラクチャの動作をシミュレート...
official
provider-actions
hashicorp
プラグインフレームワークを使用して、リソースライフサイクルイベントで命令型のTerraformプロバイダーアクションを実装します。作成前/後および更新前/後のライフサイクルトリガーをサポートします(Terraform 1.14.0では破棄イベントは利用不可)。適切なスキーマ定義、正しいフレームワークタイプ、コレクション用のElementType、および入力検証用のバリデータが必要です。長時間実行操作のための進捗報告、タイムアウト管理、包括的なエラーハンドリングを含みます。ポーリングおよび...を実装します。
official
aws-ami-builder
hashicorp
Packerのamazon-ebsビルダーを使用してカスタムAmazonマシンイメージを構築します。ソースAMIからHCLテンプレートを使用してAMI作成を自動化し、プロビジョナー(シェルスクリプト、ファイルアップロード、構成管理)によるカスタマイズをサポートします。ami_regionsによるマルチリージョンAMI配布と、名前、所有者、仮想化タイプによる柔軟なソースAMIフィルタリングをサポートします。環境変数、AWS認証情報ファイル、またはIAMインスタンスプロファイルを介して認証し、テンプレートの検証およびビルドコマンドを含みます...
official
new-terraform-provider
hashicorp
Plugin Frameworkを使用して新しいTerraformプロバイダーをスキャフォールディングします。標準の「terraform-provider-」命名規則に従った新しいGoモジュールワークスペースを生成し、必要な依存関係を初期化します。カスタマイズ用のTODOマーカー付きで、HashiCorpのPlugin Frameworkパターンに従ったテンプレートmain.goファイルを提供します。ビルドおよびテストコマンドを実行してプロバイダーがコンパイルされ、初期チェックを通過することを確認することでセットアップを検証します。新しいワークスペースを作成する前に意図を確認することでワークスペース管理を処理します...
official
azure-verified-modules
hashicorp
AVM準拠を目指すAzure Terraformモジュールの認定要件とベストプラクティス。プロバイダーのバージョン制約(azurerm >= 4.0, < 5.0; azapi >= 2.0, < 3.0)を適用し、gitベースのモジュール参照を禁止して、固定されたTerraformレジストリソースを推奨。すべての識別子にスネークケース(小文字)を必須とし、正確な変数型、アンチコリューション層パターンによる個別の出力属性、アルファベット順のローカル変数を要求。新しいリソース追加には機能トグル変数を必要とする...
official