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
- One image definition per OS. Windows Server 2025 from the Marketplace is a Generation 2 image (
2025-datacenter-g2). Create a new gallery image definition withHyperVGeneration = V2and keep the old one: it is your rollback. - Pin what your jobs depend on. "Latest" breaks without warning. Examples from this refresh:
- The latest PowerShell 7 release shipped no
win-x64.msi, so an install script that looked up "latest" installed nothing, and the build still succeeded. Pin the MSI URL of an LTS release. - Keep exact versions for the modules and tools the jobs call: 7Zip4Powershell, the SQL Server Command Line Utilities (bcp, sqlcmd).
- Pin Packer itself and check its SHA256. Declare the plugin versions in
required_pluginsand runpacker init.
- The latest PowerShell 7 release shipped no
- Side-by-side installs. ODBC Driver 17 and 18 installers have the same file name (
msodbcsql.msi): download them into two folders. The same goes for SqlPackage: the MSI builds (.NET Framework) install into...\160\DAC\binand...\170\DAC\bin. The .NET zip build is a separate copy, which PowerShell 7 can load as DacFx; keep it off the PATH. - Make the build fail when something is missing. At the end of each install script, check
pwsh.exe,Get-OdbcDriver, everySqlPackage.exe, andthrowif one is missing. A green build with a missing component costs much more later. - Windows updates: each build starts from the current Marketplace image and installs the pending updates (
windows-updateprovisioner), so a rebuild is also a patch run.
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
- A Batch pool accepts a new
imageReferenceorvmSizeonly when it has 0 nodes and its allocation state isSteady. - Change the existing pool, do not create a new one: jobs and application configs point to the pool id.
- Change only the image (and the VM size when needed). Send back the rest of
virtualMachineConfigurationas it is: the subnet, identities, autoscale formula and start task are left untouched. - Do region A, then region B. The old image version stays in the gallery for the rollback.
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
- Test pool: a fixed-scale pool with the same subnet, identities and VM size as production, 0 nodes at rest. Switch it first.
- 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.
- 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 samecommandLine,applicationPackageReferences,userIdentityandoutputFiles, give it a new id and setmaxTaskRetryCount = 0. Only pick tasks that are safe to run twice (exports, backups, index maintenance), never cleanup jobs. - 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. - Put the test pool back to 0, and delete the test job.
Pitfalls
- Gen1 / Gen2: the first switch from a Gen1 to a Gen2 image usually needs another VM size too.
- Expired rights: a time-limited role (PIM, for example) can expire in the middle of the work. A scheduled "resize to 0 later" then fails with
PermissionDenied, and the node keeps running and costing money. - Do not redeploy every pool to change one image: when the infrastructure code that defines the pools has drifted from the live pools (autoscale formulas changed by hand, for example), a full redeployment can overwrite those changes. Patch the one pool you need.
- Keep the infrastructure code in line: after the switch, update the image version in the pool definitions, so the next deployment does not put the old image back.