Back to Terraform

Azure Compute: VMs, Scale Sets, Disks and Application Health

November 6, 2026 Wasil Zafar 25 min read

Release compute capacity with verified images, identities and load-balancing behavior

Table of Contents

  1. Choose Availability, Zone and SKU Constraints Explicitly
  2. Version Images, Extensions and Bootstrap Inputs
  3. Connect NICs, Managed Identities and Disks
  4. Compare Load Balancer and Application Gateway Responsibilities
  5. Rehearse a Scale-Set Change and Inspect Leftovers

Choose Availability, Zone and SKU Constraints Explicitly

Placement is three decisions wearing one name. A region fixes the data boundary, a zone fixes the failure domain inside it, and a SKU fixes the hardware. Azure validates them separately, so a plan can look internally consistent while asking for a shape the subscription cannot buy.

Zone count is a property of the region. A region advertises one, two or three zones, and no subscription setting adds a fourth. Spreading members across zones 1, 2 and 3 survives a datacenter failure; spreading them across two zones in a two-zone region survives less than the diagram implies.

An availability set is the older contract. It groups VMs into fault domains and update domains inside one datacenter and tops out at a 99.95 percent SLA. It cannot span zones, its fault domains stop at three, and membership is fixed when the VM is created.

A zone-pinned VM trades coverage for locality. Pinning keeps latency to zonal services low and lets a zonal disk attach, but every member in that zone shares one failure. The 99.99 percent tier needs a spread across zones or a zone-redundant front end.

A zonal disk decides the zone of everything attached to it. A managed disk records its zone at creation, and a VM in another zone cannot attach it. That is the real constraint behind "just move the VM": the disk moves first, or the data does.

Zone spanning is a creation-time choice. Uniform scale sets take a zone list, Flexible sets take a fault-domain count, and changing either is a rebuild rather than an edit. Size the autoscale maximum so one zone's members can be lost without dropping below the floor.

Uniform and Flexible are different resources, not a setting. The Uniform model manages instances you never address and treats the fleet as one object; the Flexible model exposes each member as a real VM you can patch, tag and mix by SKU. Flexible suits heterogeneous or long-lived members, Uniform suits a fleet that really is identical.

SKU availability is filtered three times. The region must offer the size, each zone must list it, and the subscription must not carry a restriction for it. The listing from az vm list-skus exposes those restrictions and the zones a size supports, so a size that appears in the region can still be absent from zone 2.

Quota is counted per family, per region. A subscription can hold plenty of total vCPU and still refuse one more D-series member. Check family quota before the surge, because a rolling upgrade that cannot add a member stalls halfway and leaves two versions serving.

A capacity reservation is the only promise that outlives demand. It holds SKU capacity in a chosen zone for a fixed term and bills whether or not members use it. Reserve for the floor you must keep, not for the peak you hope to reach.

Features narrow the list again. Trusted launch needs a Gen2 image and a compatible size; an ephemeral OS disk needs enough local temp storage; Premium SSD v2 needs a zone and a supported size. Any one of them can disqualify a SKU that quota and zones allowed.

Figure 1 follows the checks in the order that eliminates candidates fastest.

Choose Availability, Zone and SKU Constraints Explicitly
%%{init: {'theme':'base','themeCSS':'.edgeLabel .label text, .edgeLabel text, .edgeLabel span { fill:#132440 !important; color:#132440 !important; }','themeVariables': {'primaryColor':'#16476A','primaryTextColor':'#ffffff','primaryBorderColor':'#132440','secondaryColor':'#3B9797','secondaryTextColor':'#ffffff','secondaryBorderColor':'#132440','tertiaryColor':'#c4873b','tertiaryTextColor':'#132440','tertiaryBorderColor':'#132440','lineColor':'#5a6e82','textColor':'#132440','titleColor':'#132440','mainBkg':'#16476A','nodeBorder':'#132440','clusterBkg':'#eef3f7','clusterBorder':'#132440','edgeLabelBackground':'#ffffff','actorBkg':'#16476A','actorTextColor':'#ffffff','actorBorder':'#132440','activationBkgColor':'#3B9797','activationBorderColor':'#132440','signalColor':'#5a6e82','signalTextColor':'#132440','noteBkgColor':'#c4873b','noteTextColor':'#132440','noteBorderColor':'#132440','labelBoxBkgColor':'#a8dede','labelBoxBorderColor':'#132440','labelTextColor':'#132440','loopTextColor':'#132440','altBackground':'#f8f9fa','fontFamily':'DM Sans, sans-serif'}}}%%
flowchart TD
    R["Region selected
zone count is fixed"] --> Z{"How many zones?"} Z -->|"one, no zone support"| A["Availability set
three fault domains, 99.95 percent"] Z -->|"two"| T["Two-zone spread
weaker than it looks"] Z -->|"three"| S["Zone list 1, 2, 3"] S --> K{"SKU listed in every zone?"} K -->|"no"| X1["Member pinned to one zone"] K -->|"yes"| Q{"Family vCPU quota for a surge?"} Q -->|"no"| X2["Rolling upgrade stalls midway"] Q -->|"yes"| F{"Gen2, temp disk and zone features met?"} F -->|"no"| X3["Apply rejects the size"] F -->|"yes"| C["Capacity reservation for the floor"] C --> OK["Zone-spanning scale set
release planned"] T --> K A --> OK classDef primary fill:#132440,color:#ffffff,stroke:#0b172b; classDef secondary fill:#16476A,color:#ffffff,stroke:#0f314a; classDef ok fill:#3B9797,color:#ffffff,stroke:#2a6f6f; classDef danger fill:#BF092F,color:#ffffff,stroke:#7a0420; classDef warn fill:#c4873b,color:#132440,stroke:#8a5a1f; class R,Z,K,Q,F primary; class S,T,A secondary; class C,OK ok; class X1,X2,X3 danger;

Figure 2 places the same checks on the subscription boundary, because quota and SKU restrictions live outside the region box.

Three zones inside one region, three checks outside it Placement, SKU and quota are three separate checks Region: the zone count is fixed here Zone 1 Member scale set instance Shares the zone failure with every peer placed here. Zone 2 Member scale set instance Reservation holds the SKU Zone 3 Member scale set instance Zonal disk zone 3 only Zone-redundant front end spans all three zones The zone list is chosen once, at creation. Editing it later is a rebuild, not a plan. Checks outside the region Family vCPU quota room for a surge member SKU allowed per zone restrictions are per zone Feature requirements Gen2, temp disk, zone A size that passes quota can still fail a zone check. All three must pass together. An availability set is one datacenter, three fault domains and a 99.95 percent SLA.

Version Images, Extensions and Bootstrap Inputs

A member is assembled from four independently versioned layers. The platform image carries the operating system, extensions add agents and configuration, custom data bootstraps the instance, and the application artifact carries the code. Terraform sees the first three references and only a version string for the fourth.

A Marketplace image with a floating version is a plan that lies. Writing latest into the image reference leaves the plan unchanged when the publisher ships a new build, so rebuilt members quietly differ from the ones already running. Pin a version, or move to a gallery image id that a build job owns.

The gallery is where an image becomes a release. A gallery image version holds replicas per target region, an end-of-life date and an exclusion flag, and its version number is what a scale set consumes. Publishing a version is a build job; pointing the scale set at it is the reviewable change.

Build outside the state file. Image Builder, Packer or a pipeline produces the version, and Terraform only records which version is current. A build that runs inside apply turns a failed package install into half-created infrastructure that the next plan has to explain.

Extensions are code with a version and a time budget. Each extension names a publisher, a type and a handler version, and the whole set shares a provisioning budget before the platform declares failure. Pinning the handler version keeps a silent publisher update out of a release you approved.

Extension order is a dependency, not a preference. An agent that starts before the runtime exists records nothing, so list the prerequisite in the ordering field and let the platform wait. A custom script runs once per provisioning, which means a reboot does not re-run it and a new trigger does.

Protected settings are write-only to the API, not to state. The service will not return them, but the plan file and the state file still hold the values, so a certificate or token placed there is a stored secret with a longer life than the VM. Read secrets at boot through the workload identity instead.

Custom data is small, opaque and one-shot. The size cap, base64 encoding and single delivery make it a bootstrap channel rather than a configuration system. It is also not returned by the API, so a running member and its state entry can disagree with no field to compare.

Bootstrap inputs deserve the same diff as the scale set. The payload, the extension settings and the artifact version are all text, so a reviewer can read them before apply. A boot that fetches configuration by branch name is a boot whose inputs nobody reviewed.

Run Command is a diagnostic, not a deployment. It executes against one live member, changes nothing in the image, and vanishes at the next replacement. A fix applied that way is a fix the next scale-in will test.

The application artifact is the cheap rollback. Baking code into the image makes every release an image build plus a fleet replacement. A versioned artifact makes rollback a version number and a restart, and the image changes only when the runtime does.

Provenance joins the layers. One release identifier on the image version, the artifact and the scale set tag lets a running member trace back to a single pipeline run. Tags are the cheapest carrier because they stay queryable in the gallery long after the build agent is gone.

Figure 3 shows the four layers converging on one boot, and the ways that boot can diverge from the plan.

Version Images, Extensions and Bootstrap Inputs
%%{init: {'theme':'base','themeCSS':'.edgeLabel .label text, .edgeLabel text, .edgeLabel span { fill:#132440 !important; color:#132440 !important; }','themeVariables': {'primaryColor':'#16476A','primaryTextColor':'#ffffff','primaryBorderColor':'#132440','secondaryColor':'#3B9797','secondaryTextColor':'#ffffff','secondaryBorderColor':'#132440','tertiaryColor':'#c4873b','tertiaryTextColor':'#132440','tertiaryBorderColor':'#132440','lineColor':'#5a6e82','textColor':'#132440','titleColor':'#132440','mainBkg':'#16476A','nodeBorder':'#132440','clusterBkg':'#eef3f7','clusterBorder':'#132440','edgeLabelBackground':'#ffffff','actorBkg':'#16476A','actorTextColor':'#ffffff','actorBorder':'#132440','activationBkgColor':'#3B9797','activationBorderColor':'#132440','signalColor':'#5a6e82','signalTextColor':'#132440','noteBkgColor':'#c4873b','noteTextColor':'#132440','noteBorderColor':'#132440','labelBoxBkgColor':'#a8dede','labelBoxBorderColor':'#132440','labelTextColor':'#132440','loopTextColor':'#132440','altBackground':'#f8f9fa','fontFamily':'DM Sans, sans-serif'}}}%%
flowchart TD
    S["Source commit
one release id"] --> I["Image build
outside Terraform"] S --> P["Artifact build
immutable version"] I --> G["Gallery image version
pinned number"] P --> O["Blob or registry
digest addressable"] G --> V["Scale set image reference"] V --> E["Extensions
publisher, type, handler version"] E --> D["custom_data
base64, one-shot"] D --> B["Member boots"] O -.->|"fetched at boot"| B B --> H{"Probe passes on its own state?"} H -->|"no"| X1["Member replaced, batch stalls"] H -->|"yes"| OK["In service"] G -.->|"floating version"| X2["Clean plan, stale image"] D -.->|"secret pasted in"| X3["Credential in state"] E -.->|"budget exceeded"| X4["Provisioning fails"] classDef primary fill:#132440,color:#ffffff,stroke:#0b172b; classDef secondary fill:#16476A,color:#ffffff,stroke:#0f314a; classDef ok fill:#3B9797,color:#ffffff,stroke:#2a6f6f; classDef danger fill:#BF092F,color:#ffffff,stroke:#7a0420; classDef warn fill:#c4873b,color:#132440,stroke:#8a5a1f; class S,B,H primary; class I,P,G,O,V,E,D secondary; class OK ok; class X1,X2,X3,X4 danger;

Connect NICs, Managed Identities and Disks

A VM is a compute object, not a bundle. Its network interface, public address, data disks and identity are separate resources with their own names and lifecycles. Terraform destroys exactly what it created, which is why the bundle shown in the portal and the graph held in state rarely agree.

The NIC carries the address, so it outlives a rebuild. A network interface created on its own is detached when the VM is deleted and stays in the resource group, holding its private address and any public IP. Delete it deliberately, or the next VM cannot take the address it expects.

Scale-set interfaces are the exception. A Uniform set creates one interface per instance, deletes it with the instance, and does not support attaching a second one. Anything a member must keep beyond its own life has to live outside the set.

A Standard public address is static, zonal or zone-redundant. Basic SKU addresses are retired, and a Standard load balancer accepts only Standard addresses. A zonal address pins the front end to one failure domain, which quietly undoes a zone-spanning backend.

System-assigned identity dies with the VM; user-assigned identity does not. The first is convenient for a single resource and disappears with it, leaving role assignments that outlive their principal and render as unknown identities. The second is a resource you name, reuse and clean up on purpose.

The identity is only half the grant. A role assignment scoped to a Key Vault lets the member read a secret at boot; without it the identity is a name with no permissions. Both resources belong in the same review as the scale set, not in a follow-up ticket.

An independently created disk survives the VM. A managed disk that Terraform owns on its own is detached rather than deleted when the VM goes away, and it bills at its provisioned size until something removes it. A disk declared inside the VM or instance model is deleted with its owner.

Attachment is a resource and a failure point. The attachment names a LUN and a caching mode, and one disk cannot be attached twice. Detach before deleting, because an active attachment fails the delete rather than the plan, and the error arrives late.

Temp storage is not a disk you can keep. The local temp disk belongs to the host, is lost on deallocation or a size change, and backs an ephemeral OS disk. Anything written there is a cache with a lifetime, not data.

A data disk needs an owner before it needs a size. Decide whether the disk follows the VM, outlives it, or is mounted by another member; only the first belongs in the instance model. The other two are separate resources with their own destroy behaviour and their own review.

Disk size only grows. Expanding a managed disk is an in-place operation that the guest must then acknowledge; shrinking means a new disk and a copy. Premium SSD v2 is zonal and cannot be an OS disk, and Ultra needs a supported size in a supported zone.

Key changes are migrations. A disk encryption set binds a disk to a key and a vault, and moving to a different key is a re-encryption path rather than a field edit. Decide the key, the vault and the access model before the first disk exists.

Figure 4 draws the ownership boundary: what the VM takes with it, and what it merely borrowed.

What the VM owns, borrows and leaves behind Destroy the VM and three different things happen Destroyed with the VM OS disk managed or ephemeral Extensions agents and scripts Instance NIC in a set one per member Attached, not owned NIC and public IP survive as orphans Managed data disk detached, still billing Disk encryption set key binding outlives it Outlives the VM User-assigned identity reused by the next member Role assignment scope, not a credential Key Vault and secrets read at boot by identity detach grant The destroy plan removes the VM and its OS disk, nothing else. The NIC, address, data disk and role assignment stay until a separate owner removes them.

Compare Load Balancer and Application Gateway Responsibilities

The two services sit at different layers and answer different questions. A load balancer moves TCP and UDP flows to healthy endpoints; Application Gateway reads HTTP requests, terminates TLS and decides by path or host. Choosing the wrong one shows up later as a feature that cannot be added.

Load Balancer Standard is a flow distributor. It hashes the five-tuple by default, offers a static front end that can be zone-redundant, and carries outbound rules for egress. It never reads a URL, so path routing and header rules are outside its contract.

Application Gateway v2 is a reverse proxy with a policy layer. Listeners, routing rules, backend settings and probes are separate objects, and a WAF policy attaches at the front end. Because it terminates TLS, certificates and renewals live here rather than on every member.

A health probe is a contract with the application. The probe path must answer from the instance's own state, not from a shared dependency, or one slow database marks the whole pool unhealthy at once. Match the status codes the application really returns, including the redirect it uses for HTTP.

Probe placement decides who removes a member. A load balancer probe takes a member out of the backend pool, while a scale-set health probe lets the platform replace it. Configure both, or unhealthy members accumulate while the pool quietly shrinks.

The host header breaks more probes than the path does. An application that serves by hostname returns an error to a probe addressed by IP, and the pool empties while every member is healthy. Point the probe at the backend hostname, or let it take the host from the backend settings.

Path-based routing is the reason to pay for layer seven. A URL path map sends one hostname's paths to different pools, which a flow distributor cannot express. The cost is a rule per path and a probe per pool, and a path that matches nothing lands on the default backend's error page.

WAF mode is a decision, not a default. Detection logs what it would block; prevention returns the block. Turning prevention on without a baseline produces outages that read like application bugs, so run detection through a full traffic cycle first.

TLS termination moves the certificate, not the trust. Between gateway and member the traffic is a new connection, so re-encryption needs a certificate the member trusts, and plain HTTP inside the network is a decision with a boundary attached. Neither option is free.

Subnets are part of the contract. Application Gateway v2 needs a dedicated subnet and inbound management traffic from the gateway service tag on the documented port range; a load balancer probe arrives from the platform address and needs the load balancer tag allowed.

Outbound is a separate decision from inbound. A Standard load balancer provides egress only through outbound rules or a NAT gateway, and Application Gateway carries no general egress for its backends. A member that must reach a registry needs its own path out.

Zone redundancy is a tier, not a checkbox. Both services reach it through their Standard and v2 tiers, and the retired tiers cannot restore it. Read the SKU before the zone plan, because the older tier silently removes the option the design depends on.

ResponsibilityLoad Balancer, StandardApplication Gateway, v2What breaks if you choose wrong
Layer and protocolTCP and UDP flowsHTTP and HTTPS requestsPath or host rules need layer seven
TLSpasses encrypted bytes throughterminates, then re-encryptsRenewal lands on the wrong owner
Routingfive-tuple hash or client IPpath, host, header, redirectOne pool per app, no shared front door
Health probeport check, or HTTP statuspath with status match and hostA 401 health path empties the pool
Request inspectionnoneWAF policy with managed rulesA body-borne attack passes unread
Zone redundancyzone-redundant static front endzone-redundant v2 front endThe retired tier removes the option
Outbound trafficoutbound rules or NAT gatewaybackend responses onlyMembers cannot reach a registry
Session affinityfive-tuple, optional client IPcookie-based affinityState hides in a cookie nobody owns

Figure 5 follows one request through the layer-seven path and then shows what the layer-four path cannot see.

Layer seven path with a probe ejection, and the layer four contrast One request, two layers of decision Client HTTPS 443 Application Gateway v2 Listener and WAF certificate ends here Path /api to pool rule, not a hash Probe /healthz host and status match Backend pool zone spanning Member 1 healthy receives traffic Member 2 healthy receives traffic Member 3 probe 401 ejected, not replaced probe verdict is membership The same request through Load Balancer Standard Client TCP 443 Load balancer flow hash, no URL Member terminates TLS certificate per instance No path rule, no WAF, no cookie affinity at this layer.

Rehearse a Scale-Set Change and Inspect Leftovers

Change capacity before you change the image. A count change exercises the quota, the zone balance and the probe without touching the release artifact, so a failure names one cause instead of three. Rehearse it in a sandbox with the same SKU and zone list as production.

Lab

Rehearse a Scale-Set Change and Inspect Leftovers

Status: design-only. No Azure subscription or credential was used to produce this article, and these steps were not executed here. Versions: Terraform CLI 1.17.1, hashicorp/azurerm 5.13.0, verified 6 November 2026.

Prerequisites. A sandbox subscription guarded by an allowed subscription id, the application VNet and subnet from the networking article, a gallery image version, a Standard load balancer with an HTTP probe, and family quota for one extra member. Start from a Uniform scale set of two members across three zones.

Minimal setup. A rolling upgrade policy, a health probe owned by the load balancer, autoscale disabled so the count is the only variable, and a request loop that closes each connection.

ObjectLab value
Scale setUniform, three zones, two members, rolling upgrade
SKUD-series with premium storage, zone 1 to 3 allowed
Imagegallery version pinned by number, not a floating tag
Probeapplication path, two-probe threshold, host header set
Count changetwo to three, then back to two
Request loopone request per second, connection closed per request
  1. Baseline. Record the member count, the per-zone distribution and the error rate over five minutes. Do not change anything while the baseline is still interesting.
  2. Record the reference. Write down the image version and the current instance count. Those two values are the rollback target for the whole exercise.
  3. Change one number. Raise the count from two to three, and nothing else. A plan that also replaces members has a second change hiding in it.
  4. Read the plan body. Expect an in-place count update with no member replacement. A replacement here means an argument outside the count forced it.
  5. Apply and watch admission. Note when the third member appears, when the probe passes, and whether the other two stayed in service.
  6. Poll the per-zone split. Two members across three zones leave one zone empty. Note whether the third fills it or repeats a zone that already has a member.
  7. Scale back down. Return to two and watch which member leaves. An abrupt drop in healthy targets points at a probe or drain setting, not at Terraform.
  8. Check the member view. Confirm the image version each member reports, and compare it with the version recorded in step 2.
  9. Destroy the lab. Apply a reviewed destroy plan, then list what remains rather than assuming the resource group is empty.
  10. Audit leftovers. Walk the resource types below, because a successful destroy is not the same as a clean subscription.
LeftoverWhy it survivesWhere to look
Managed data diskseparate resource, detached not deleteddisks in the resource group
NIC and private IPcreated on its own, holds the addressnetwork interfaces without an owner
Public IP addressStandard addresses are staticaddresses not associated
Role assignmentscope outlives a system-assigned principalaccess control on the vault
Boot diagnostics containerstorage account is not part of the setdiagnostics settings on the account
Saved plan filewritten by the operator, not the providerplan artifacts in the workspace

Expected observation. A sequence rather than a duration: count recorded, plan showing one in-place change, third member admitted, per-zone split noted, scale-in returning to two, destroy completing, and a short list of resources that were never the scale set's to delete.

Failure checks. A plan that replaces members points at an argument outside the count. A third member that never passes the probe points at the host header, the health path or a subnet rule. A scale-in that resets connections points at drain or probe timing. Leftover disks and addresses point at resources created outside the set's lifecycle.

Cost dimensions. Member hours including the third instance, premium disk GB-month for OS and data disks, load balancer hours and rules, public address hours, and the retained capacity reservation if one was booked. The lab is small; the orphaned disk is what keeps billing.

Cleanup. Detach and delete the managed data disk, release the public address, delete the interface, remove the role assignment before the identity, delete the diagnostics container, and confirm the zone list and count are back to the recorded baseline. Keep the previous image version until the rollback window closes, and keep state out of Git.

References (verified 6 November 2026):

  • azurerm_linux_virtual_machine_scale_set: https://registry.terraform.io/providers/hashicorp/azurerm/5.13.0/docs/resources/linux_virtual_machine_scale_set
  • azurerm_orchestrated_virtual_machine_scale_set: https://registry.terraform.io/providers/hashicorp/azurerm/5.13.0/docs/resources/orchestrated_virtual_machine_scale_set
  • azurerm_managed_disk: https://registry.terraform.io/providers/hashicorp/azurerm/5.13.0/docs/resources/managed_disk
  • azurerm_application_gateway: https://registry.terraform.io/providers/hashicorp/azurerm/5.13.0/docs/resources/application_gateway
  • Availability sets and zones: https://learn.microsoft.com/en-us/azure/virtual-machines/availability
  • Scale set orchestration modes: https://learn.microsoft.com/en-us/azure/virtual-machine-scale-sets/virtual-machine-scale-sets-orchestration-modes
  • Application Gateway health probes: https://learn.microsoft.com/en-us/azure/application-gateway/application-gateway-probe-overview

Next in the Series

In Azure Storage: Blob Access, Data-Plane Permissions and State Backends, we'll explore Manage account and container configuration while separating network access, authorization and stored data.