Azure SDK for PythonでActivity Logsを取得する

AzureのPython SDKでActivity Logを取得する方法を調べました。

f:id:yomon8:20220303221102p:plain

使うモジュールについて

そもそもどのモジュールで取得するのかわからなかったのですが、以下のIssueにヒントがありました。

Is it possible to extract Activity Logs for a subscription as seen in azure console using the sdk? · Issue #18670 · Azure/azure-sdk-for-python · GitHub

こちらに記載されている ActivityLogsOperations を使うようです。

docs.microsoft.com

ActivityLogsOperations のコードはこちら になります。

ただ、コードを読むとわかるのですが、ActivityLogsOperations は直接使うものではなく、こちらの MonitorManagementClientを通して使います。

サンプルコード

Activity Logsを取得・出力するサンプルコードです。

azure-mgmt-monitorazure-identity をpipでインストールしておきます。

import os
from datetime import datetime, timedelta

from azure.identity import DefaultAzureCredential
from azure.mgmt.monitor import MonitorManagementClient

os.environ["AZURE_TENANT_ID"] = "xxxxxxx"
os.environ["AZURE_CLIENT_ID"] = "xxxxxxx"
os.environ["AZURE_CLIENT_SECRET"] = "xxxxxxx"

subscription_id = "xxxxxxx"
credential = DefaultAzureCredential()

client = MonitorManagementClient(credential=credential, subscription_id=subscription_id)


# 直近6時間分の特定ResourceGroupのログを取得
to_dt = datetime.utcnow()
from_dt = to_dt - timedelta(hours=6)
resource_group = "my-rg"
log_filter = f"eventTimestamp ge '{from_dt.isoformat()}Z' and eventTimestamp le '{to_dt.isoformat()}Z' and resourceGroupName eq '{resource_group}'"

# 取得する項目を選択
fields = "operationName,status,eventTimestamp,resourceGroupName,level"

log_entries = client.activity_logs.list(filter=log_filter, select=fields)
for entry in log_entries:
    e = entry.as_dict()
    print(f"{e['level']}|{e['operation_name']['localized_value']}|{e['status']['localized_value']}|{e['event_timestamp']}|{e['resource_group_name']}")
    print("-" * 30)

出力は以下のようになります。

Informational|Create or Update Virtual Machine|Succeeded|2022-03-03T11:09:08.467917Z|my-rg
------------------------------
Informational|Create or Update Network Security Group|Succeeded|2022-03-03T11:09:06.219394Z|my-rg
------------------------------
Informational|Create or Update Virtual Network|Succeeded|2022-03-03T11:09:05.918008Z|my-rg
------------------------------
Informational|Create or Update Public Ip Address|Succeeded|2022-03-03T11:09:03.423489Z|my-rg
省略......

filterselect に指定する項目は以下のコメントを読むとわかります。

https://github.com/Azure/azure-sdk-for-python/blob/azure-mgmt-monitor_3.0.0/sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2015_04_01/aio/operations/_activity_logs_operations.py#L50-L79