Handle events, deadlines, cancellation, and reporting
Suppose orders-02 fails a health check just before the orders-01 patch window. Restarting the canary could leave Contoso without a replica that can serve orders. Someone must recognize the failed check, request cancellation while there's still time, and confirm whether installation was stopped. The on-call operator needs a way to do that even if the automated handler never starts.
Azure Event Grid delivers pre- and post-maintenance notifications. A successful delivery means the endpoint received the event, not that its checks passed. A failed, missing, or timed-out pre-event handler doesn't automatically cancel patch installation. A run marked Succeeded tells you that update installation succeeded. It doesn't tell you whether the pre- or post-event handler succeeded or whether the application works.
For a 15:00 UTC start, the operator can use 14:40 to detect a missing job and 14:45 to decide whether to cancel. These are example operating margins, not service deadlines.
For a 15:00 start, Microsoft recommends completing edits to an existing maintenance configuration by 14:00 because a cached policy can still trigger the old schedule. That recommendation applies to configuration edits, not VM startup. A maintenance configuration doesn't start a stopped or deallocated VM. Azure requires the VM to be running at least 15 minutes before installation; this campaign needs it running before 14:20 so the operator can complete the prechecks. Keep unrelated shutdown automation out of the run and recovery period. Allow approved patch reboots, and don't schedule an automatic shutdown at window end while installation or recovery might still be running.
Use this timeline to decide who acts and when:
| Time (UTC) | Owner | Action |
|---|---|---|
By 14:00, if changing an existing configuration |
Patch operator | Complete the schedule change for the intended 15:00 run in line with Microsoft's one-hour cached-policy mitigation recommendation. Inspect the planned occurrences; don't treat an edit as cancellation of an existing occurrence. |
Before 14:20 |
Patch operator | Complete planned VM starts, initial readiness checks, and target-assignment changes. Save the approved configuration ID, assignment IDs, and full list of VM resource IDs for this run. |
About 14:20 to 14:30 |
Event Grid | Deliver the pre-event. Multiple pre-events run independently, not in sequence; budget for all checks within the 20-minute pre-event period. |
By 14:40 |
On-call operator | Check for a pre-event job for this occurrence. Investigate missing delivery or authentication immediately; don't wait until the window opens. |
By 14:45 |
Handler or operator | If the pre-event handler hasn't recorded PRE_PASS for this run by 14:45, request cancellation. Then check whether the run status changes to Cancelled. |
By 14:50, or earlier if the event specifies |
Handler or operator | For a 15:00 UTC start, request cancellation by 14:50 at the latest. If the event's CancellationCutOffDateTime is earlier (for example, 14:47), use that earlier deadline. Don't rely on a later timestamp from a sample payload. |
15:00 through window end |
Update Manager and guest | Unless canceled, install eligible updates and perform any required reboot. |
| At completion or window end | Event Grid and application owner | Inspect the post-event job and check the application after recovery. The owner authorizes traffic restoration only after direct checks pass. Post-event work can extend outside the window. |
Design a handler that acts only on an approved run
An Automation implementation needs a published runbook and a runtime validated with its actual webhook input. The Update Manager runbook tutorial specifies PowerShell 7.4, while the Automation webhook documentation warns about PowerShell 7 webhook-input conversion and recommends PowerShell 5. Both 7.4 and 5.1 are supported Automation runtime versions, but that doesn't resolve the webhook-specific documentation conflict. Don't assume that every 7.4 webhook fails or that runtime support proves this input path works.
Before assigning production VMs, exercise the actual Event Grid-to-webhook-to-published-runbook path with a separately approved nonproduction configuration. Confirm that the event body can be parsed, expected configuration and run identifiers can be validated, the managed identity can read the approved scope, and the cancellation and post-event paths produce the intended records. An HTTP 202 response means the runbook was queued, not that these actions completed.
Record the runtime and tested versions of Az.Accounts, Az.Resources, Az.ResourceGraph, and, if using VM Run Command, Az.Compute. Disable process-level context autosave, connect with Connect-AzAccount -Identity, and set the approved subscription context explicitly. If the webhook input path can't be established, leave production waves unscheduled and use another documented handler approach, such as an Event Grid-triggered Azure Function, or resolve the runtime choice with evidence. Revalidate the chosen implementation rather than assuming a runtime downgrade alone fixes it.
Azure infrastructure handles Event Grid subscription validation for a direct Automation webhook or an Event Grid-triggered Function. A custom HTTP endpoint has its own validation responsibilities. Endpoint ownership validation, job queueing, and handler completion are separate checks; don't add manual subscription-handshake logic to the Automation runbook as a remedy for a payload-parsing failure.
For a verified, approved pre-event, establish that the occurrence is still eligible for pre-work: it hasn't been canceled or closed and has no recorded stop decision. Then confirm that the remaining replica can carry the workload. Use the approved maintenance/readiness control to prevent new production requests from reaching the canary, then confirm that in-flight work has completed or reached an application-approved safe state. Bound this work so there's still time to request and confirm cancellation before the earlier of the event cutoff and ten minutes before the start. Record PRE_PASS only after the required checks and drain complete. Don't let a delayed event begin a new disruptive drain after the decision deadline.
With Azure Load Balancer, a probe-down result stops new connections to that backend but doesn't prove established TCP connections have ended. A successful probe after boot can also make a backend eligible before an order lookup has been validated. Use the application's approved readiness or traffic-control mechanism; don't use a listening TCP port as proof that business operations work. Don't block the probe with a network security group as a substitute for a designed drain procedure.
Keep the canary isolated from production traffic during installation, reboot, and its direct application checks. The workload owner still needs a way to send a test request to the patched instance. Keep read-only checks separate from the approved, time-limited actions that change traffic. If a check times out, don't assume the command stopped inside the VM.
Use these steps to ensure the handler changes traffic only for an approved maintenance run:
- Store the approved configuration ID, VM IDs, subscription and group boundaries, expected principal ID, and approval expiry outside the event payload. Protect these inputs from writes by the handler. Store each wave's approval separately. Set it to remain valid until the run's post-event checks finish, but require fresh approval for the next scheduled run.
- Under the configuration's Events, subscribe only to
Microsoft.Maintenance.PreMaintenanceEventandMicrosoft.Maintenance.PostMaintenanceEventusing the Event Grid schema. If using a runbook webhook, use a short-lived URL, store it as a secret, and redact it from logs. Confirm endpoint validation and monitor delivery failures and failed Automation jobs. - Check the event type, topic,
data.MaintenanceConfigurationId, and full run correlation ID against the trusted configuration and expected occurrence. If the handler receives an unexpected batch of events or an event from an unapproved source, reject it and alert the operator. Don't use that event to run a command on a VM or cancel a maintenance run. The operator must independently identify the approved run if delivery or authentication failed. - Before starting new pre-event traffic actions, read the current status of the verified named maintenance occurrence and check its recorded approval and stop decision. A confirmed
Cancelledoccurrence or a closed campaign occurrence isn't eligible for a new drain, even if its event arrives before the decision deadline. Don't start new pre-work while a recorded cancellation decision is awaiting confirmation. Record the event receipt and the reason for taking no new action; don't create a newPRE_PASSfor a stopped occurrence. - If the current disposition can't be established, treat the precheck as inconclusive and don't change traffic. The operator must independently establish the verified occurrence's state and, if cancellation is still needed and timely, request it before the earlier of the event cutoff and ten minutes before the start, then confirm
Cancelled. Keep current-state eligibility separate from event deduplication: the first delivery of an old event can still be ineligible. - Use durable records keyed by configuration, run, event type and event ID to recognize redelivery; check run state before repeating a cancellation. Before changing traffic state, use a single create-if-absent operation to record which handler claimed the action. Only the handler that creates the record should perform it. Record the action's completion or failure separately from the claim, so an interrupted action isn't mistaken for a successful drain.
- For a known pre-event, confirm the approval hasn't expired and the handler can see all target subscriptions. Check that assignments and selection tags haven't changed, compare the run's VM IDs with the approved IDs, confirm candidate updates still satisfy the approved software change, and check workload health and remaining capacity. Complete the approved, bounded traffic drain before recording
PRE_PASSwith the run and event IDs. Record it only if every required check and action passes. If any check fails or is inconclusive, explicitly request cancellation for the verified run before the earlier ofCancellationCutOffDateTimeand start minus ten minutes. Limit how long the handler waits for each guest check so it can still cancel. A timeout stops the wait, not the command inside the VM; use it for read-only observations, not unbounded changes. - For a post-event, verify the run and its targets again before collecting observations. Report the post-handler result separately. Don't restore production traffic just because the event arrived; the workload owner must accept the direct application checks and authorize restoration.
A status read isn't an atomic lock across Azure and the application. Coordinate the operator's stop decision with new action claims in the run record, and reconcile any action already in progress. Don't infer eligibility solely from the absence of an earlier claim, or require Pending as the only possible pre-event state without a documented contract for that implementation.
For example, a pre-event emitted at 14:25 might first be handled at 14:35, after the operator confirmed cancellation at 14:30. It's still before the 14:45 decision deadline, but the canceled occurrence can't authorize a new drain. Record the receipt and its disposition without changing traffic or issuing a new PRE_PASS.
Keep write privileges narrower than read visibility. If used, Microsoft.Compute/virtualMachines/runCommand/action belongs only on approved VMs; it allows code execution even if the intended command is read-only. Scope Microsoft.Maintenance/applyUpdates/read and Microsoft.Maintenance/applyUpdates/write to the approved maintenance configuration. Don't grant subscription-wide write access to solve an inventory problem.
Request and confirm cancellation
The handler or authorized operator can cancel a known, approved occurrence when a precheck fails. Monitor each occurrence independently of the handler. For example, for a 15:00 UTC start, alert the operator by 14:40 if no pre-event job has started. A handler that never starts can neither send its own alert nor cancel the run. To request cancellation and confirm its outcome:
- Match the occurrence in maintenance history to the approved configuration and start time. Its correlation ID must be the full resource path
{approved-configuration-id}/providers/Microsoft.Maintenance/applyUpdates/{run-name}. Reject any other path. Calculate the deadline in UTC: use the earlier of the pre-event'sCancellationCutOffDateTimeand ten minutes before the scheduled start. Leave time to send the request and confirm the outcome. - Record the decision to stop the verified occurrence in the campaign's shared durable run record before requesting cancellation when that can be done without delaying the request. If the record can't be written, report the recording failure and continue the independent Azure cancellation path; don't wait for the customer record store to recover or let the cancellation deadline expire. If the handler can't establish whether the run was stopped, treat its status as unknown and leave traffic unchanged. The customer record doesn't cancel Azure patching or replace confirmation of the named run's outcome. If a traffic action was already in progress, reconcile its actual result with the workload owner rather than assuming that the stop decision or cancellation request interrupted it.
- Use the verified correlation ID as
{run-resource-id}, including the leading/subscriptions/. On the authenticated Azure Resource Manager endpoint,GETthat run. If its status is alreadyCancelled, record the result. Otherwise, while cancellation is still needed and timely,PUT{"properties":{"status":"Cancel"}}to that run, not the configuration or VM. - Record the request time, response and run ID. Read the status of the same run until
properties.statusisCancelledor the time limit expires. If the time limit expires first, record the cancellation as unconfirmed. An accepted request, a runbook exception, or a status ofPendingorInProgressisn't confirmation.
PUT {run-resource-id}?api-version=2023-09-01-preview
Content-Type: application/json
{"properties":{"status":"Cancel"}}
GET {run-resource-id}?api-version=2023-09-01-preview
The request uses the named-run Create Or Update Or Cancel operation. Don't replace the verified run name with default from the different Create Or Update operation. The cancellation response might already contain Cancelled. If it doesn't, read the same run until you confirm the outcome or reach the time limit. These reads confirm cancellation; the API doesn't necessarily require asynchronous polling.
Find the run in Azure Update Manager > History using its correlation ID. For each target VM, check whether installation started and whether the workload is healthy. Record both results. If the cutoff was missed, the request failed, or confirmation is missing, hold later waves and assume installation may proceed. Escalate to the workload owner, monitor actual targets, and use the approved recovery procedure if needed. Deleting an assignment isn't a way to stop an in-flight installation. Confirmed cancellation stops only the identified occurrence, not tomorrow's schedule.