Listings: Een plek voor VMs binnen je Cloud Native landschap? Het kan met Packer! uit SDN Magazine #145

Listing 1: Aanmaken van een SIG:

# Resource group en image gallery
az group create --name myGalleryRG --location westeurope
az sig create --resource-group myGalleryRG --gallery-name myGallery

# Standaard Windows definitie
az sig image-definition create \
   --resource-group myGalleryRG \
   --gallery-name myGallery \
   --gallery-image-definition myImageDefinition \
   --publisher myPublisher \
   --offer myOffer \
   --sku mySKU \
   --os-type Windows \
   --hyper-v-generation V2 \
   --os-state Generalized

Listing 2: HCL:

 

build.pkr.hcl
build {
  sources = ["source.azure-arm.windows2022"]

  provisioner "powershell" {
    script = "scripts/main.ps1"
  }
}
sources.pkr.hcl
source "azure-arm" "windows2022" {
  location = "westeurope"

  tenant_id   	  = var.tenant_id
  subscription_id = var.subscription_id
  client_id   	  = var.client_id
  client_secret   = var.client_secret

  managed_image_resource_group_name = "myGalleryRG"
  managed_image_name                = "myImageDefinition-1.0.0"

  image_offer 	  = "WindowsServer"
  image_publisher = "MicrosoftWindowsServer"
  image_sku   	  = "2022-datacenter-azure-edition"
  os_type     	  = "Windows"
  vm_size     	  = "Standard_D2s_v4"

  communicator   = "winrm"
  winrm_use_ssl  = true
  winrm_insecure = true
  winrm_timeout  = "10m"
  winrm_username = "packer"

  subscription    	= var.subscription_id
  resource_group  	= "myGalleryRG"
  gallery_name    	= "myGallery"
  image_name      	= "myImageDefinition"
  image_version   	= "1.0.0"
}

Listing 3: PowerShell file:

scripts/main.ps1
# Start of script
$InstallSourcePath = 'C:\Install'
New-Item $InstallSourcePath -ItemType "directory" -Force

# Start downloading Azure CLI
Invoke-WebRequest -Uri https://aka.ms/installazurecliwindows -OutFile $InstallSourcePath\AzureCLI.msi

# Start install Azure CLI
Start-Process -filepath msiexec.exe -Wait -ErrorAction Stop -ArgumentList "/I $InstallSourcePath\AzureCLI.msi /qn"   	 

# SysPrep machine
Write-Log "Starting Sysprep"
& $env:SystemRoot\\System32\\Sysprep\\Sysprep.exe /oobe /generalize /quiet /quit /mode:vm
	while($true) { $imageState = Get-ItemProperty HKLM:\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Setup\\State | Select-Object ImageState; if($imageState.ImageState -ne 'IMAGE_STATE_GENERALIZE_RESEAL_TO_OOBE') { Write-Output $imageState.ImageState; Start-Sleep -s 10  } else { break } }
}

# Cleanup downloads
Remove-Item -Path "$InstallSourcePath" -Recurse -Force

Listing 6: VMSS Opspinnen:

az group create --name myResourceGroup --location eastus
az vmss create \
   --resource-group myResourceGroup \
   --name myScaleSet \
   --image "/subscriptions//resourceGroups/myGalleryRG/providers/Microsoft.Compute/galleries/myGallery/images/myImageDefinition" \
   --generalized