🌳

KQL クエリで差分チェック

2024/05/29に公開

はじめに

Azure Automation のインベントリなど、Log Analytics ワークスペースに保存したログで過去と差分比較できないかと思いまして、KQL クエリを作成してみました。

検証方法

Azure Automation インベントリを使用して、マシンにインストールされているアプリケーションの追加、削除、更新 (バージョンアップ) を可視化します。ConfigrationData テーブルを使用して指定した過去日数のログと現在のログを比較します。今回のサンプルでは差分チェックのために join で現在と過去の結果を結合します。更新は inner で結合し該当箇所の変更確認、追加/削除は leftanti を使用して一致していないレコードを抽出します。
https://learn.microsoft.com/ja-jp/azure/automation/change-tracking/overview-monitoring-agent?tabs=win-az-vm
https://learn.microsoft.com/ja-jp/azure/data-explorer/kusto/query/join-inner
https://learn.microsoft.com/ja-jp/azure/data-explorer/kusto/query/join-leftanti

KQL クエリと実行結果

let diffdays = 7d;
// 昨日~今日のインベントリ レコードを取得し、各 Computer, SoftwareName, Publisher ごとにレコードを取得
let now = ConfigurationData
| where SoftwareType == "Application"
| where TimeGenerated > startofday(now()-1d)
| summarize arg_max(TimeGenerated, *) by Computer, SoftwareName, Publisher
| project Computer, SoftwareName, Publisher, CurrentVersion;
// X 日前のデータを取得し、各 Computer, SoftwareName, Publisher ごとにレコードを取得
let before = ConfigurationData
| where SoftwareType == "Application"
| where  TimeGenerated between (startofday(now() - diffdays -1d) .. startofday(now() - diffdays))
| summarize arg_max(TimeGenerated, *) by Computer, SoftwareName, Publisher
| project Computer, SoftwareName, Publisher, CurrentVersion;
//最新と過去のデータを inner join で結合し、CurrentVersion が異なるレコードをフィルタリングして DeltaType に "Updated" を設定
let updated = now
| join kind=inner (before) on Computer, SoftwareName, Publisher
| where CurrentVersion != CurrentVersion1
| project Computer, SoftwareName, Publisher, CurrentVersion, DeltaType = "Updated";
// 最新データから、過去データと updated データに存在しないレコードを leftanti join を使ってフィルタリングし、DeltaType を "Added" に設定
let added = now
| join kind=leftanti (before) on Computer, SoftwareName, Publisher, CurrentVersion
| join kind=leftanti (updated) on Computer, SoftwareName, Publisher
| extend DeltaType = "Added";
// 過去データから、最新データと updated データに存在しないレコードを leftanti join を使ってフィルタリングし、DeltaType を "Removed" に設定
let removed = before
| join kind=leftanti (now) on Computer, SoftwareName, Publisher, CurrentVersion
| join kind=leftanti (updated) on Computer, SoftwareName, Publisher
| extend DeltaType = "Removed";
// 追加されたデータ、削除されたデータ、および更新されたデータを結合
union added, removed, updated

注意点

  • 過去ログを参照するため、ログの保存期間に注意が必要
  • Azure Automation インベントリの場合、マシンが起動していない/削除したなどでログが記録されていない場合はすべて差分として表示されてしまう
Microsoft (有志)

Discussion