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
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
Terraform 테스트 작성 및 실행을 위한 종합 가이드로, 어설션, 모킹, 모듈 검증을 포함합니다. .tftest.hcl 구문을 사용하여 테스트 파일을 작성하며, plan 또는 apply 모드로 실행되는 run 블록을 지원하고, 선택적 상태 격리와 함께 순차 및 병렬 실행을 지원합니다. 리소스 속성, 출력, 데이터 소스에 대한 조건을 어설션하고, expect_failures를 사용하여 잘못된 입력이 적절히 거부되는지 검증합니다. Mock 제공자(Terraform 1.7.0+)는 인프라 동작을 시뮬레이션합니다...
official
provider-actions
hashicorp
Plugin Framework를 사용하여 리소스 수명 주기 이벤트에서 명령형 Terraform Provider 작업을 구현합니다. 생성 전/후 및 업데이트 전/후 수명 주기 트리거를 지원합니다(소멸 이벤트는 Terraform 1.14.0에서 사용 불가). 올바른 프레임워크 유형, 컬렉션용 ElementType, 입력 검증용 유효성 검사기를 포함한 적절한 스키마 정의가 필요합니다. 장기 실행 작업을 위한 진행 보고, 타임아웃 관리, 포괄적인 오류 처리를 포함합니다. 폴링 및...
official
aws-ami-builder
hashicorp
Packer의 amazon-ebs 빌더로 사용자 지정 Amazon 머신 이미지를 구축합니다. HCL 템플릿과 프로비저너(셸 스크립트, 파일 업로드, 구성 관리)를 사용해 소스 AMI에서 AMI 생성을 자동화합니다. ami_regions를 통한 다중 리전 AMI 배포와 이름, 소유자, 가상화 유형별 유연한 소스 AMI 필터링을 지원합니다. 환경 변수, AWS 자격 증명 파일 또는 IAM 인스턴스 프로파일을 통해 인증하며 템플릿 검증 및 빌드 명령을 포함합니다...
official
new-terraform-provider
hashicorp
Plugin Framework를 사용하여 새로운 Terraform Provider를 스캐폴딩합니다. 표준 "terraform-provider-" 명명 규칙을 따르는 새로운 Go 모듈 워크스페이스를 생성하고 필요한 종속성을 초기화합니다. HashiCorp의 Plugin Framework 패턴을 따르는 템플릿 main.go 파일을 제공하며, 사용자 정의를 위한 TODO 마커가 포함되어 있습니다. 빌드 및 테스트 명령을 실행하여 Provider가 컴파일되고 초기 검사를 통과하는지 확인함으로써 설정을 검증합니다. 새 워크스페이스를 생성하기 전에 의도를 확인하여 워크스페이스 관리를 처리합니다.
official
azure-verified-modules
hashicorp
Azure Terraform 모듈이 AVM 규정을 준수하기 위한 인증 요구 사항 및 모범 사례입니다. 공급자 버전 제약 조건(azurerm >= 4.0, < 5.0; azapi >= 2.0, < 3.0)을 적용하고, git 기반 모듈 참조를 금지하며 고정된 Terraform 레지스트리 소스를 사용하도록 합니다. 모든 식별자에 소문자 스네이크 케이스, 정확한 변수 유형, 반부패 계층 패턴을 통한 개별 출력 속성, 알파벳 순서로 정렬된 로컬 변수를 요구합니다. 새 리소스가 추가될 때 기능 토글 변수를 요구합니다...
official