如何使用 alerts/powershell/cli 获取 Azure Activity 日志摘要?

How to get Azure Activity Log Summary with alerts/powershell/cli?

我目前正在尝试监视我们的订阅示例中发生的任何 RBAC 更改:John.Doe 将 Sue.Jones 作为 Reader 添加到资源组 rg-test。有没有什么可以实现我正在尝试使用 powershell/cli/rest。根据我的尝试和研究,它不是。

查看 activity 日志,对于 Write RoleAssignments 操作,摘要包含我需要的所有输出,但在使用 powershell/cli 时,您无法获得分配的角色或分配给谁的信息.在 summary 你得到:

操作名称

编写角色分配

时间戳

周三(东部夏令时间)

事件发起者:John.Doe

消息与 'Sue.Jones' 共享。

角色:Reader

范围资源组:'rg-test'

使用 powershell/cli/您收到的警报

Activity 日志警报 alert-iamtesting 时间 2021 年 5 月 19 日 15:29 UTC 类别行政 操作名称 Microsoft.Authorization/roleAssignments/write

关联 ID 0000000-000000000-000000000

信息级

资源 ID /subscriptions/0000000-000000000-000000000/resourceGroups/rg-test/providers/Microsoft.Authorization/roleAssignments/0000000-000000000-000000000

来电者John.Doe

属性 {"statusCode":"Created","serviceRequestId":"0000000-000000000-000000000","eventCategory":"Administrative","entity":"/subscriptions/0000000-000000000-000000000/resourceGroups/rg-test/providers/Microsoft.Authorization/roleAssignments/00000000000000000

当您在 Azure 门户中查看 activity 日志时,它会调用 3 API 个端点。

第一个是Activity Logs - List:

GET https://management.azure.com/subscriptions/{subscription id}/providers/microsoft.insights/eventtypes/management/values?api-version=2017-03-01-preview&$filter=eventTimestamp ge '2021-05-19T19:52:43Z' and eventTimestamp le '2021-05-20T01:52:43Z' and eventChannels eq 'Admin, Operation' and resourceGroupName eq '{resource group name}' and operations eq 'Microsoft.Authorization/roleAssignments/write' and levels eq 'Critical,Error,Warning,Informational'

它returns 调用者, operationName, eventTimestamp, resourceGroup目标用户的对象id角色的RoleDefinitionId

第二个获取目标用户:

GET https://graph.windows.net/hanxia.onmicrosoft.com/users/{user object id}?api-version=1.6

最后一位获得角色:

GET https://management.azure.com/subscriptions/{subscription id}/providers/Microsoft.Authorization/roleDefinitions/{RoleDefinitionId}?api-version=2015-07-01

因此您可以获得所需的所有信息。

当我们使用Azure CLI时,我们应该选择az monitor activity-log listBUT 它只相当于上面的第一个调用。我们得到一个名为 resourceId 的 属性,它是角色分配 ID。

所以我们还需要获取带有id的roleAssignment。这是一个简单的脚本。

# list the activity logs of resource group "AllenTestRG01" in the past 4 hours
$logs = az monitor activity-log list -g AllenTestRG01 --offset 4h | ConvertFrom-Json

# I assume that the first $logs[0] is the log you are tracking. (you should implement your logic here to find the log you need)
$logs[0].resourceId

# list the role assignments for resource group "AllenTestRG01"
$assignments = az role assignment list -g AllenTestRG01 | ConvertFrom-Json

# do a match
foreach ($assignment in $assignments){
    if ($assignment.id -eq $a[0].resourceId) {
        Write-Host "assigned user: " $assignment.principalName  " role: " 
$assignment.roleDefinitionName
    }
}