LLI Wiki — My Digital Knowledge Base

Azure Batch: build a custom Windows node image with Packer and move a pool to it

Build a Windows Server node image with Packer into an Azure Compute Gallery, test it on a test pool, then switch Batch pools to it (and back).

How to build the node image of an Azure Batch pool with Packer, store it in an Azure Compute Gallery, test it, and move the pools to it without touching anything else in the pool. Written after a refresh from Windows Server 2022 to Windows Server 2025 for pools that run PowerShell 7, bcp exports and SqlPackage bacpac jobs.

All names below are placeholders: <subscription-id>, <gallery>, <batch-account>, <pool-id> and so on.

Overview

flowchart TD
    subgraph Build["1. Build (CI pipeline)"]
        A["Pipeline run, image = win2025"]
        B["Azure CLI task, workload identity federation, no secret"]
        C["Packer, pinned version, use_azure_cli_auth"]
        D["Temporary VM, Windows Server 2025 Gen2"]
        E["Install scripts: PowerShell 7, ODBC 17 and 18, bcp, SqlPackage, modules"]
        F["Windows Update and reboot"]
        G["Checks: build fails if a component is missing"]
        H["Sysprep"]
    end
    subgraph Gallery["2. Azure Compute Gallery"]
        I["Image definition win2025 Gen2, version 1.0.N"]
        J["Replica region A"]
        K["Replica region B"]
    end
    subgraph Pools["3. Batch pools"]
        L["Test pool: switch, inventory, copies of real tasks"]
        M["Production pool region A, 0 nodes: PATCH image and VM size"]
        N["Production pool region B, 0 nodes: PATCH image and VM size"]
        R["Rollback: PATCH back to the previous version"]
    end
    A --> B
    B --> C
    C --> D
    D --> E
    E --> F
    F --> G
    G --> H
    H --> I
    I --> J
    I --> K
    J --> L
    L -->|OK| M
    L -->|OK| N
    K --> N
    M -.->|problem| R
    N -.->|problem| R

Build the image

What matters in the recipe

Authentication without a secret

The pipeline step runs in an Azure CLI task whose service connection uses workload identity federation. Packer reuses that session:

source "azure-arm" "image" {
  use_azure_cli_auth = true            # no client id / secret in the template or pipeline
  os_type            = "Windows"
  image_publisher    = "MicrosoftWindowsServer"
  image_offer        = "WindowsServer"
  image_sku          = "2025-datacenter-g2"
  vm_size            = var.vm_size

  shared_image_gallery_destination {
    subscription         = var.subscription_id
    resource_group       = var.gallery_resource_group
    gallery_name         = var.gallery_name
    image_name           = "batchimage-win2025"
    image_version        = var.image_version
    replication_regions  = ["<region-a>", "<region-b>"]
  }
}

The federated token lasts about one hour. A build that takes longer fails with AADSTS700024. If that happens, use a service connection backed by a managed identity instead.

Choose the VM size

A Gen2 image only runs on sizes that support Gen2. Check this before switching a pool. For example, Standard_F16 is Gen1 only, while Standard_D16ds_v4 supports Gen1 and Gen2 and has a 600 GB temporary disk D:, where Batch puts the task working folders.

Get-AzComputeResourceSku -Location '<region>' |
  Where-Object { $_.ResourceType -eq 'virtualMachines' -and $_.Name -eq 'Standard_D16ds_v4' } |
  ForEach-Object { ($_.Capabilities | Where-Object Name -eq 'HyperVGenerations').Value }   # V1,V2

Check also the quota of the VM family on the Batch account. A family with no quota cannot be used, even if the size exists in the region.

Rules of the switch

Commands

1. Check the new image version

Get-AzGalleryImageVersion -ResourceGroupName '<gallery-rg>' -GalleryName '<gallery>' `
  -GalleryImageDefinitionName 'batchimage-win2025' -Name '1.0.N' |
  Select-Object Name, ProvisioningState, @{ n = 'Regions'; e = { $_.PublishingProfile.TargetRegions.Name -join ', ' } }

ProvisioningState must be Succeeded, with a replica in the region of the pool.

2. Read the pool and switch it

$path    = '/subscriptions/<subscription-id>/resourceGroups/<batch-rg>/providers/Microsoft.Batch/batchAccounts/<batch-account>/pools/<pool-id>?api-version=2024-07-01'
$imageId = '/subscriptions/<subscription-id>/resourceGroups/<gallery-rg>/providers/Microsoft.Compute/galleries/<gallery>/images/batchimage-win2025/versions/1.0.N'

$pool = (Invoke-AzRestMethod -Method GET -Path $path).Content | ConvertFrom-Json
$pool.properties.currentDedicatedNodes, $pool.properties.allocationState    # must be 0 and Steady
$pool.properties.deploymentConfiguration.virtualMachineConfiguration.imageReference.id   # keep it: rollback

# Same configuration, only the image replaced
$vmc = $pool.properties.deploymentConfiguration.virtualMachineConfiguration
$vmc.imageReference = @{ id = $imageId }
$body = @{ properties = @{
    vmSize                  = 'Standard_D16ds_v4'          # leave out to keep the current size
    deploymentConfiguration = @{ virtualMachineConfiguration = $vmc }
} } | ConvertTo-Json -Depth 20

Invoke-AzRestMethod -Method PATCH -Path $path -Payload $body

It is worth wrapping this in a small script with a dry run by default: print the current and target values and the blockers (nodes > 0, not Steady, no replica in the region, version not Succeeded, VM size without Gen2), and send the PATCH only with -Apply.

3. Bring an autoscale pool to 0 for a few minutes

An autoscale pool cannot be resized by hand, and a formula with a minimum node count during office hours never reaches 0. Replace the formula for a moment:

$ctx  = Get-AzBatchAccount -AccountName '<batch-account>' -ResourceGroupName '<batch-rg>'
$pool = '<pool-id>'

$original = (Get-AzBatchPool -BatchContext $ctx -Id $pool).AutoScaleFormula     # keep it

# Temporary formula: always 0 (single quotes, or PowerShell eats the $ variables)
Enable-AzBatchAutoScale -BatchContext $ctx -Id $pool `
  -AutoScaleFormula '$TargetDedicatedNodes=0; $NodeDeallocationOption=taskcompletion;' `
  -AutoScaleEvaluationInterval ([TimeSpan]::FromMinutes(10))

# Repeat until Steady / 0
Get-AzBatchPool -BatchContext $ctx -Id $pool | Select-Object AllocationState, CurrentDedicatedComputeNodes

# ... switch the image (step 2) ...

# Original formula back
Enable-AzBatchAutoScale -BatchContext $ctx -Id $pool -AutoScaleFormula $original `
  -AutoScaleEvaluationInterval ([TimeSpan]::FromMinutes(10))

Run these one at a time. If you paste the whole block, the switch runs while the pool is still Resizing and is refused. Then the original formula comes back, and you start again. While the formula is 0, new tasks wait in the queue; they start as soon as the formula is back. See also Azure Batch pool autoscale formula.

4. Rollback

The same PATCH as in step 2, with the previous image version id and the previous VM size (a Gen1 size such as Standard_F16 is fine again with a Gen1 image). The pool must be at 0 nodes again.

Test before production

  1. Test pool: a fixed-scale pool with the same subnet, identities and VM size as production, 0 nodes at rest. Switch it first.
  2. Inventory: start one node, run a read-only task that lists the OS build, installed programs, ODBC drivers, executables on the PATH, SqlPackage copies and PowerShell modules, then compare with the old image. That is how you find the surprises: here a runtime that the old image had and the new one did not (.NET 6, out of support), and an ODBC driver patch that was newer than the one installed by the build.
  3. Real tasks: read a real task of each application with the Batch REST API (GET /jobs/{job}/tasks/{task}) and add a copy to a test job bound to the test pool. Keep the same commandLine, applicationPackageReferences, userIdentity and outputFiles, give it a new id and set maxTaskRetryCount = 0. Only pick tasks that are safe to run twice (exports, backups, index maintenance), never cleanup jobs.
  4. RDP (optional): add a user on the node (New-AzBatchComputeNodeUser). The node has no public IP, so connect from a machine inside the virtual network.
  5. Put the test pool back to 0, and delete the test job.

Pitfalls

Mastodon LLIMastodon SocialFosstodon