Skip to content

From Exposure to Fix: Connecting Microsoft Perception to Your Image Pipeline

This is Part 2 of a two-part series. Part 1 explained how Microsoft Perception works: red, blue and green team agents, Microsoft-published playbooks, and sessions that record every step. This part puts it to work for an Azure platform team.


[Add link to Part 1 once it is published]


1. The gap between “fix this first” and the fix


Perception is very good at answering one hard question: out of hundreds of findings, which ones actually matter? The Posture Prioritization Agent ranks issues by real-world risk, exposure, exploitability and asset criticality, and explains what to fix first and why.


For many Azure estates, though, the fix for a vulnerable VM does not happen on the VM. If your workloads run from a golden image in Azure Compute Gallery, patching machines one by one creates drift: the next scale-out or rebuild brings the vulnerability straight back. The durable fix is to rebuild the image, validate it, publish a new version and roll it out.


That is exactly the pipeline we built earlier in this blog series with Packer and Azure DevOps. This article connects the two: Perception decides what matters and a person approves it; a small, auditable bridge works out which images are affected and queues the existing image pipeline to rebuild them.


2. What we are building



The flow has five stages:



  1. Decide – run a Perception playbook, review the session and approve the CVEs to act on.

  2. Find – use Defender advanced hunting to list the devices exposed to those CVEs.

  3. Map – use Azure Resource Graph to map those VMs to the Compute Gallery image they were built from.

  4. Rebuild – queue the image pipeline for each affected image, with the CVE IDs recorded as the reason.

  5. Verify – once the new image is rolled out, confirm in Defender that the exposure is gone.


Two design rules run through every stage:



  • A person approves the hand-off. Nothing is rebuilt just because an agent said so. The bridge only acts on CVE IDs a person has reviewed in a Perception session.

  • Only documented interfaces. The bridge uses public APIs (Microsoft Graph advanced hunting, Azure Resource Graph and the Azure DevOps Pipelines REST API). It does not depend on any undocumented Perception internals.


3. Prerequisites



  • Perception enabled in your tenant, with Defender unified RBAC turned on and the agents used by your chosen playbook set up. Check Microsoft Learn for current availability.

  • Defender Vulnerability Management data for your VMs (for example through Defender for Servers or Defender for Endpoint), so the DeviceTvmSoftwareVulnerabilities table is populated.

  • An image pipeline in Azure DevOps that builds, validates and publishes to Azure Compute Gallery, such as the one from Part 1 of the image automation series.

  • An identity for the bridge with:

    • Microsoft Graph application permission ThreatHunting.Read.All to run advanced hunting queries.

    • Reader on the subscriptions that hold your VMs, for Resource Graph.

    • Permission to queue the image pipeline in Azure DevOps.



  • Python 3.10 or later.


4. Step 1 – Decide in Perception


Start in the Microsoft Defender portal and select Perception. Two documented playbooks fit this scenario well:



  • Plan for posture remediation builds a prioritised remediation plan across clouds, devices and AI, weighing exposure, exploitability and asset context.

  • Protect against a threat starts from a threat intelligence source and produces attack path analysis, posture findings, prioritised remediation and new detection rules.


Run the playbook from the Playbooks page (or describe the goal in New Chat), then open the session. Review the agents’ reasoning and the prioritised list. Where agents ask for input, approve, reject or redirect them as you would with a colleague.


The output we need is small: the CVE IDs the team agrees to fix through the image pipeline. Record them with the session link in your change ticket. This is the human checkpoint, and the session gives you the audit trail for why the rebuild happened.



Tip: Not every finding belongs in the image pipeline. Configuration issues or excess permissions surfaced by the Recon Agent are usually fixed in Bicep, policy or identity settings. Send only software vulnerabilities baked into the image down this path.



5. Step 2 – Find the exposed devices


Advanced hunting in Defender exposes vulnerability data in the DeviceTvmSoftwareVulnerabilities table, including the device, software, CVE ID and severity. Try the query in the portal first (Hunting > Advanced hunting):


// Devices exposed to the CVEs approved in the Perception session
let approvedCves = dynamic([“CVE-YYYY-NNNNN”]); // replace with the CVE IDs from your session
DeviceTvmSoftwareVulnerabilities
| where CveId in~ (approvedCves)
| summarize Cves = make_set(CveId),
Software = make_set(strcat(SoftwareName, ” “, SoftwareVersion)),
Severity = max(VulnerabilitySeverityLevel)
by DeviceId, DeviceName, OSPlatform

You should see each exposed VM, the vulnerable software and the CVEs that affect it. If the list is empty, check that the VMs are onboarded and reporting vulnerability data.


6. Step 3 – Map devices to gallery images


Defender knows which machines are vulnerable; Azure knows which image each VM came from. Azure Resource Graph joins the two quickly across subscriptions. This query lists every VM built from a Compute Gallery image, with its computer name for matching:


resources
| where type =~ ‘microsoft.compute/virtualmachines’
| extend computerName = tolower(tostring(properties.osProfile.computerName)),
imageId = tolower(tostring(properties.storageProfile.imageReference.id))
| where imageId contains ‘/galleries/’
| project name, resourceGroup, subscriptionId, computerName, imageId

Matching on computer name is simple and works well when VM host names are unique, which is common in platform-managed estates. If your naming is less strict, add another key such as subscription or resource group. The query covers single VMs; extend it with microsoft.compute/virtualmachinescalesets if you run scale sets.


7. Step 4 – The remediation bridge


The bridge is a short Python script that runs both queries, groups the results by image definition and, only when asked, queues the image pipeline. It defaults to a dry run, so the first thing you see is a report, not a pipeline run.


“””exposure_to_image.py – map approved CVEs to Compute Gallery images and queue rebuilds.

Dry run by default. Pass –queue to start the image pipeline for each affected image.
“””
import argparse, os, re, requests
from collections import defaultdict
from azure.identity import DefaultAzureCredential
from azure.mgmt.resourcegraph import ResourceGraphClient
from azure.mgmt.resourcegraph.models import QueryRequest

GRAPH = “https://graph.microsoft.com/v1.0/security/runHuntingQuery”
ADO_SCOPE = “499b84ac-1321-427f-aa17-267ca6975798/.default” # Azure DevOps resource ID
IMAGE_RE = re.compile(r”/galleries/([^/]+)/images/([^/]+)”)

def hunt(cred, cves):
cve_list = “, “.join(f'”{c}”‘ for c in cves)
query = f”””DeviceTvmSoftwareVulnerabilities
| where CveId in~ ({cve_list})
| summarize Cves = make_set(CveId) by DeviceId, DeviceName”””
token = cred.get_token(“https://graph.microsoft.com/.default”).token
r = requests.post(GRAPH, json={“Query”: query},
headers={“Authorization”: “Bearer ” + token}, timeout=60)
r.raise_for_status()
# DeviceName is an FQDN; keep the host part to match the VM computer name
return {row[“DeviceName”].split(“.”)[0].lower(): row[“Cves”]
for row in r.json()[“results”]}

def gallery_vms(cred, subscriptions):
query = “””resources
| where type =~ ‘microsoft.compute/virtualmachines’
| extend computerName = tolower(tostring(properties.osProfile.computerName)),
imageId = tolower(tostring(properties.storageProfile.imageReference.id))
| where imageId contains ‘/galleries/’
| project name, computerName, imageId”””
client = ResourceGraphClient(cred)
return client.resources(QueryRequest(subscriptions=subscriptions, query=query)).data

def queue_rebuild(cred, image_definition, cves):
org, project, pipeline_id = (os.environ[k] for k in (“ADO_ORG”, “ADO_PROJECT”, “ADO_PIPELINE_ID”))
token = cred.get_token(ADO_SCOPE).token
url = f”https://dev.azure.com/{org}/{project}/_apis/pipelines/{pipeline_id}/runs?api-version=7.1″
body = {“templateParameters”: {“imageDefinition”: image_definition,
“triggerReason”: “perception-remediation”,
“cveIds”: “,”.join(sorted(cves))}}
r = requests.post(url, json=body, headers={“Authorization”: “Bearer ” + token}, timeout=60)
r.raise_for_status()
return r.json()[“_links”][“web”][“href”]

def main():
p = argparse.ArgumentParser()
p.add_argument(“–cve”, action=”append”, required=True, help=”CVE ID approved in the Perception session”)
p.add_argument(“–subscription”, action=”append”, required=True)
p.add_argument(“–queue”, action=”store_true”, help=”queue pipeline runs (default: dry run)”)
a = p.parse_args()

cred = DefaultAzureCredential()
exposed = hunt(cred, a.cve)
impact = defaultdict(lambda: {“vms”: [], “cves”: set()})
for vm in gallery_vms(cred, a.subscription):
cves = exposed.get(vm[“computerName”])
m = IMAGE_RE.search(vm[“imageId”])
if cves and m:
key = f”{m.group(1)}/{m.group(2)}” # gallery/imageDefinition
impact[key][“vms”].append(vm[“name”])
impact[key][“cves”].update(cves)

if not impact:
print(“No gallery-based VMs are exposed to the selected CVEs.”)
for image, info in impact.items():
print(f”{image}: {len(info[‘vms’])} VM(s), CVEs {sorted(info[‘cves’])}”)
if a.queue:
print(” queued:”, queue_rebuild(cred, image.split(“/”)[1], info[“cves”]))

if __name__ == “__main__”:
main()


A few points about the design:



  • One rebuild per image, not per VM. Twenty exposed VMs from the same image result in one pipeline run.

  • The reason travels with the run. The CVE IDs and trigger reason are passed as pipeline parameters, so they appear in the run history.

  • Standard authentication. DefaultAzureCredential works with a managed identity, a workload identity in a pipeline, or your own sign-in for testing. No secrets are stored in the script.


Run it:


pip install azure-identity azure-mgmt-resourcegraph requests
export ADO_ORG=<your-org> ADO_PROJECT=<your-project> ADO_PIPELINE_ID=<image-pipeline-id>

# 1. Dry run: see which images are affected
python exposure_to_image.py –cve CVE-YYYY-NNNNN –subscription <subscription-id>

# 2. After review, queue the rebuilds
python exposure_to_image.py –cve CVE-YYYY-NNNNN –subscription <subscription-id> –queue


8. Step 5 – Make the image pipeline remediation-aware


The pipeline needs three new parameters and a way to record why each image version was built. Here is the relevant part, added to the Part 1 pipeline:


parameters:
– name: imageDefinition
type: string
– name: triggerReason
type: string
default: scheduled
– name: cveIds
type: string
default: ”

stages:
– stage: Build # Packer build from Part 1, unchanged
# …
– stage: Validate # existing validation stage from Part 1
# …
– stage: Promote
dependsOn: Validate
jobs:
– deployment: Promote
environment: image-promotion # add an approval check on this environment
strategy:
runOnce:
deploy:
steps:
– task: AzureCLI@2
inputs:
azureSubscription: $(serviceConnection)
scriptType: bash
scriptLocation: inlineScript
inlineScript: |
az sig image-version update \
–resource-group $(galleryResourceGroup) \
–gallery-name $(galleryName) \
–gallery-image-definition ${{ parameters.imageDefinition }} \
–gallery-image-version $(imageVersion) \
–set tags.triggerReason=’${{ parameters.triggerReason }}’ \
tags.remediatedCves=’${{ parameters.cveIds }}’


Two details matter here:



  • The approval check on the promotion environment means a person still signs off before a new image version is promoted, even when the run was queued by automation.

  • Tagging the image version with remediatedCves gives you a clear link from the Perception session, to the pipeline run, to the image version that fixed it.


Because the pipeline still runs your validation stage, the rebuilt image goes through the same checks as any other release.


9. Step 6 – Roll out and verify


Roll the new image version out using your normal process: reimage, redeploy or update the scale set model. Then confirm the exposure has gone:


let approvedCves = dynamic([“CVE-YYYY-NNNNN”]);
DeviceTvmSoftwareVulnerabilities
| where CveId in~ (approvedCves)
| summarize ExposedDevices = dcount(DeviceId) by CveId

Vulnerability data is refreshed periodically, so allow time after rollout before you expect the count to reach zero. Finally, re-run the Perception playbook. The finding should drop out of the prioritised list, and the new session records that the loop is closed.


10. Governance checklist


Control Where it lives
Which CVEs to act on Human review in the Perception session
Who can read vulnerability data Graph permission ThreatHunting.Read.All on the bridge identity only
Who can see VM inventory Reader role, scoped to the right subscriptions
Accidental mass rebuilds Dry run by default; –queue is explicit
Image quality Existing validation stage in the pipeline
Promotion to production Approval check on the Azure DevOps environment
Audit trail Perception session, pipeline run parameters and image version tags


11. Limitations and what to watch



  • Preset playbooks. Perception playbooks are set by Microsoft and you cannot create custom ones in the current release, so the hand-off to the pipeline happens after the session rather than inside it.

  • The hand-off is CVE IDs. The bridge deliberately uses public Defender and Azure APIs rather than any Perception-specific interface. If Microsoft publishes documented integration points for Perception output, the manual step could become an automation rule.

  • Data freshness. Vulnerability data is not real time. Expect a delay between rollout and a clean result.

  • Matching. Computer-name matching assumes unique host names. Test it against your naming standard before you rely on it.

  • Not every fix is an image fix. Use this path for software baked into the image; use infrastructure-as-code or policy for configuration findings.


Conclusion


Perception changes where a platform team’s time goes. Instead of sorting a long vulnerability list, the team reviews a prioritised, explained set of findings in a session and approves what to act on. Everything after that is engineering the team already trusts: a query to find exposure, a map from VMs to images, and the same build, validate and promote pipeline used for every other release.


The result is a loop that runs from exposure to fix, with a person in control at the two points that matter (what to fix, and what to promote) and a clear audit trail from the Perception session to the image version that closed the gap.


References


Microsoft Tech Community originally posted this article on 23 November 2026 at 1:40 PM.

Leave a Reply