如何查询未连接到Azure Log Analytics Workspace的虚拟机列表
列出未连接Azure Log Analytics工作区虚拟机的最优方案
优先推荐使用Azure Resource Graph实现需求,它支持跨订阅批量检索资源属性,查询效率远高于逐个遍历虚拟机配置,几分钟即可完成全租户范围内的VM检测。
查询步骤
- 打开Azure门户中的Resource Graph Explorer
- 根据你的需求运行对应Kusto查询语句:
查询完全未连接任何Log Analytics工作区的VM
Resources | where type == "microsoft.compute/virtualmachines" | extend vmId = id, vmName = name, rg = resourceGroup, subId = subscriptionId | left join ( Resources | where type == "microsoft.compute/virtualmachines/extensions" | where properties.type in ("MicrosoftMonitoringAgent", "OmsAgentForLinux", "AzureMonitorWindowsAgent", "AzureMonitorLinuxAgent") | extend vmId = substring(id, 0, indexof(id, "/extensions/")) | extend connectedWorkspace = tostring(properties.workspaceId) | where isnotempty(connectedWorkspace) ) on vmId | where isempty(connectedWorkspace) | project VM名称 = vmName, 资源组 = rg, 订阅ID = subId, VM资源ID = vmId
查询未连接到指定Log Analytics工作区的VM
将下方查询语句中的<目标LA工作区ID>替换为你的工作区实际资源ID即可:
Resources | where type == "microsoft.compute/virtualmachines" | extend vmId = id, vmName = name, rg = resourceGroup, subId = subscriptionId | left join ( Resources | where type == "microsoft.compute/virtualmachines/extensions" | where properties.type in ("MicrosoftMonitoringAgent", "OmsAgentForLinux", "AzureMonitorWindowsAgent", "AzureMonitorLinuxAgent") | extend vmId = substring(id, 0, indexof(id, "/extensions/")) | extend connectedWorkspace = tostring(properties.workspaceId) | where isnotempty(connectedWorkspace) ) on vmId | where isempty(connectedWorkspace) or connectedWorkspace != "<目标LA工作区ID>" | project VM名称 = vmName, 资源组 = rg, 订阅ID = subId, 关联工作区ID = connectedWorkspace, VM资源ID = vmId
备选命令行方案
如果你习惯用命令行操作,可直接运行Azure CLI调用Resource Graph执行查询,不需要打开门户:
az graph query -q "Resources | where type == 'microsoft.compute/virtualmachines' | extend vmId = id, vmName = name, rg = resourceGroup, subId = subscriptionId | left join ( Resources | where type == 'microsoft.compute/virtualmachines/extensions' | where properties.type in ('MicrosoftMonitoringAgent', 'OmsAgentForLinux', 'AzureMonitorWindowsAgent', 'AzureMonitorLinuxAgent') | extend vmId = substring(id, 0, indexof(id, '/extensions/')) | extend connectedWorkspace = tostring(properties.workspaceId) | where isnotempty(connectedWorkspace) ) on vmId | where isempty(connectedWorkspace) | project vmName, rg, subId, vmId"
注意事项
- 执行查询的账号需要拥有对应订阅的读取权限,权限不足会导致查询结果不全
- 上述查询仅检测VM代理配置的目标工作区,若需验证代理实际和工作区的连通性,需要额外在VM内运行代理诊断工具
- 该查询同时兼容Windows、Linux虚拟机,同时覆盖旧版MMA代理和新版Azure Monitor代理的检测
内容的提问来源于stack exchange,提问作者itye1970
相关产品推荐
相关产品推荐

