Goal
You have a VM with your agents, hardening and base packages installed. You want every new VM and scale set instance to start from that exact build, in more than one region, and you want to be able to go back to the previous build if a new one is broken.
Azure Compute Gallery gives you that. It has three levels:
| Level | What it is | Example |
|---|---|---|
| Gallery | Container for image definitions, scoped to a resource group | galOpsImages |
| Image definition | The "product": OS type, generalized or specialized, Hyper-V generation, security type | ubuntu2204-base |
| Image version | One immutable build, replicated to target regions | 1.0.0, 1.1.0 |
VMs reference either a specific version or the definition, which resolves to the latest version.
Step 1: create the gallery and image definition
RG=rg-images
LOC=westeurope
GAL=galOpsImages
DEF=ubuntu2204-base
az group create -n $RG -l $LOC
az sig create -g $RG --gallery-name $GAL -l $LOC
az sig image-definition create -g $RG --gallery-name $GAL \
--gallery-image-definition $DEF \
--publisher Contoso --offer UbuntuBase --sku 22_04-gen2 \
--os-type Linux --os-state Generalized \
--hyper-v-generation V2 \
--features SecurityType=TrustedLaunch
The definition's properties must match the source VM, and you can't change most of them later:
--os-state:Generalizedmeans machine-specific data (host name, users, SSH host keys) is removed and each new VM gets fresh identity at provisioning.Specializedkeeps everything, so new VMs boot as clones of the source with the same host name and accounts.--hyper-v-generation: must match the source VM's generation (V1orV2).--features SecurityType=...: if the source VM uses Trusted Launch, the definition needs a matching security type. Check the source VM before you create the definition:
az vm show -g rg-build -n vm-build-01 \
--query "{os:storageProfile.osDisk.osType, security:securityProfile.securityType}" -o table
az vm get-instance-view -g rg-build -n vm-build-01 --query hyperVGeneration -o tsv
Step 2: prepare the source VM
For a generalized image, deprovision the guest first.
On Linux:
# Inside the VM. This removes the provisioning user and machine-specific data.
sudo waagent -deprovision+user -force
exit
On Windows, in an elevated prompt inside the VM:
C:\Windows\System32\Sysprep\sysprep.exe /generalize /oobe /shutdown
Then deallocate the VM and mark it as generalized in Azure:
az vm deallocate -g rg-build -n vm-build-01
az vm generalize -g rg-build -n vm-build-01
VM_ID=$(az vm show -g rg-build -n vm-build-01 --query id -o tsv)
Caution
After
waagent -deprovision+useror sysprep plusaz vm generalize, the source VM can no longer be started or logged into. Never generalize a production VM. Build from a dedicated build VM, or take a snapshot first if you might need the original again.
For a specialized image, skip deprovisioning. Stop the VM (or accept a crash-consistent capture) and use the VM ID directly.
Step 3: create the image version and replicate it
az sig image-version create -g $RG --gallery-name $GAL \
--gallery-image-definition $DEF \
--gallery-image-version 1.0.0 \
--virtual-machine "$VM_ID" \
--target-regions westeurope=2=standard_zrs northeurope=1=standard_lrs \
--replica-count 1 \
--end-of-life-date 2027-06-30
The --target-regions format is <region>[=<replica count>][=<storage account type>]. Regions without a count use --replica-count. Storage types are Standard_LRS, Standard_ZRS and Premium_LRS. Use ZRS in regions that support it, so a zone failure doesn't take out your only image copies. If many VMs or scale set instances are created at once from one region, add replicas there: each replica serves only a limited number of concurrent deployments. Check the current scaling guidance for that figure.
Replication can take a while for large images. Check its progress:
az sig image-version show -g $RG --gallery-name $GAL \
--gallery-image-definition $DEF --gallery-image-version 1.0.0 \
--expand ReplicationStatus \
--query "replicationStatus.summary[].{region:region, state:state, progress:progress}" -o table
To add a region later, update the version rather than rebuilding it:
az sig image-version update -g $RG --gallery-name $GAL \
--gallery-image-definition $DEF --gallery-image-version 1.0.0 \
--add publishingProfile.targetRegions name=uksouth regionalReplicaCount=1
Step 4: deploy VMs and scale sets from the gallery
DEF_ID=$(az sig image-definition show -g $RG --gallery-name $GAL \
--gallery-image-definition $DEF --query id -o tsv)
# Latest version (resolved at deployment time)
az vm create -g rg-app -n vm-app-01 --image "$DEF_ID" \
--security-type TrustedLaunch \
--admin-username azureuser --ssh-key-values ~/.ssh/id_rsa.pub
# Pinned version (repeatable, recommended for production)
az vm create -g rg-app -n vm-app-02 --image "$DEF_ID/versions/1.0.0" \
--security-type TrustedLaunch \
--admin-username azureuser --ssh-key-values ~/.ssh/id_rsa.pub
The image version must be replicated to the region where you create the VM. If it isn't, the deployment fails with an error saying the image version isn't available in that region.
For users in another subscription in the same tenant, give their deployment identity the Reader role on the gallery or image definition. That is enough to deploy from it:
GAL_ID=$(az sig show -g $RG --gallery-name $GAL --query id -o tsv)
az role assignment create --assignee "<group-or-sp-object-id>" --role Reader --scope "$GAL_ID"
Step 5: ship a new version and roll back if needed
Build 1.1.0 the same way, but keep it out of "latest" until it's tested:
az sig image-version create -g $RG --gallery-name $GAL \
--gallery-image-definition $DEF --gallery-image-version 1.1.0 \
--virtual-machine "$VM_ID_NEW" \
--target-regions westeurope=2=standard_zrs northeurope=1=standard_lrs \
--exclude-from-latest true
Deploy a test VM pinned to 1.1.0. When it passes, promote it:
az sig image-version update -g $RG --gallery-name $GAL \
--gallery-image-definition $DEF --gallery-image-version 1.1.0 \
--set publishingProfile.excludeFromLatest=false
Rollback is the same switch in reverse. Set excludeFromLatest=true on the bad version, and new deployments resolve "latest" to the previous good version. Existing VMs aren't changed.
For a scale set pinned to a version, point the model at the new (or previous) version and roll the instances:
az vmss update -g rg-app -n vmss-web \
--set virtualMachineProfile.storageProfile.imageReference.id="$DEF_ID/versions/1.1.0"
# Apply to existing instances (reimages them; local data on the OS disk is lost)
az vmss update-instances -g rg-app -n vmss-web --instance-ids "*"
Warning
update-instanceswith"*"rebuilds every instance at once. In production, update a few instance IDs at a time, use a rolling upgrade policy, or use automatic OS upgrades with health probes.
Step 6: list, retire and clean up versions
az sig image-version list -g $RG --gallery-name $GAL \
--gallery-image-definition $DEF \
--query "[].{version:name, excludeFromLatest:publishingProfile.excludeFromLatest, eol:publishingProfile.endOfLifeDate, state:provisioningState}" -o table
Deleting a version doesn't affect VMs that were already created from it. It does break any template, scale set model or pipeline that still references that version. Search for references before you delete:
az graph query -q "
resources
| where type in~ ('microsoft.compute/virtualmachines','microsoft.compute/virtualmachinescalesets')
| extend img = tostring(coalesce(properties.storageProfile.imageReference.id, properties.virtualMachineProfile.storageProfile.imageReference.id))
| where img contains '/galleries/$GAL/'
| summarize count() by img" -o table
The az graph command needs the resource-graph CLI extension. Note that the image ID recorded on a VM shows the reference used at deployment, which may be the definition ("latest") rather than a version.
az sig image-version delete -g $RG --gallery-name $GAL \
--gallery-image-definition $DEF --gallery-image-version 1.0.0
Delete in order: versions, then definitions, then the gallery. Azure rejects deleting a parent that still has children.
Common errors
| Symptom | Cause | Fix |
|---|---|---|
| Version creation fails with a Hyper-V generation or security type mismatch | Definition doesn't match the source VM | Create a new definition with matching --hyper-v-generation and --features SecurityType |
| New VMs boot with the source's host name or wait for provisioning | Specialized VM captured into a Generalized definition, or the reverse | Match --os-state to how the VM was prepared |
| VM create fails with "not available in region" | Version not replicated there | Add the region with az sig image-version update --add publishingProfile.targetRegions ... |
| "Latest" deploys an untested build | New version created without --exclude-from-latest | Exclude it now; pin production to explicit versions |
| Large scale-out is slow or fails | Too few replicas in the region | Increase the regional replica count |
Prevent it next time
- Build images in a pipeline (Azure VM Image Builder, Packer or a scripted build VM), never by hand on a server you need afterwards.
- Use semantic versions and always set
--end-of-life-dateso stale images are easy to find. - Create new versions with
--exclude-from-latest trueand promote them only after a test deployment passes. - Pin production scale sets and templates to explicit versions, and keep at least the previous good version until the next one has been in use for a full patch cycle.
- Use ZRS replicas and replicate to your DR region, so you can rebuild there without depending on the primary region.
Get the weekly HubDatAI email
One email a week with everything new: posts, learning sessions and videos. Free, no spam, unsubscribe in one click. What you get