如何使用 python 为任何资源以及 'Tags' 生成 Azure 日志 Activity 数据的报告?

How to generate reports for Azure Log Activity Data using python for any resource alongwith 'Tags'?

我的同事使用下面的 powershell 查询来检索过去 4 天(不包括今天)的日志数据,它匹配资源的操作并收集诸如 EventTimeStamp、Caller、SubscriptionId 等特征

Get-AzureRmLog -StartTime (Get-Date).AddDays(-4) -EndTime (Get-Date).AddDays(-1) | Where-Object {$_.OperationName.LocalizedValue -match "Start|Stop|Restart|Create|Update|Delete"} |
Select-Object EventTimeStamp, Caller, SubscriptionId, @{name="Operation"; Expression = {$_.operationname.LocalizedValue}},

我是 azure 的新手,我想生成一份报告,我还可以在该报告中针对过去 90 天的资源获取 'Tags' 名称和值。对此的 powershell 查询是什么?我也可以使用 python 来查询这些数据吗?我尝试搜索文档但无法深入研究,所以如果有人可以将我重定向到正确的位置,那将会很有帮助。

首先,你应该知道并不是所有的azure资源都可以指定标签,所以你应该在你的代码中考虑到这一点。请参考Tag support for Azure resources查看哪些azure资源支持标签。

对于powershell查询,我建议使用new azure powershell az module instead of the old azureRM module.

这是一个带有 az 模块 的简单 powershell 代码。出于测试目的,我只介绍如何获取标签并将其添加到输出中。请随时根据您的要求进行更改。

#for testing purpose, I just get the azure activity logs from a specified resource group
$mylogs = Get-AzLog -ResourceGroupName "a resource group name"

foreach($log in $mylogs)
{   

    if(($log.Properties.Content.Values -ne $null))
    {
        #the tags is contains in the Properties of the log entry.
        $s = $log.Properties.Content.Values -as [string]
        if($s.startswith("{"))
        {
            $log | Select-Object EventTimeStamp, Caller, SubscriptionId,@{name="Operation"; Expression = {$_.operationname.LocalizedValue}}, @{name="tags"; Expression = {($s | ConvertFrom-Json).tags}}      
        }
        #if it does not contains tags.
        else
        {
            $log | Select-Object EventTimeStamp, Caller, SubscriptionId,@{name="Operation"; Expression = {$_.operationname.LocalizedValue}}, @{name="tags"; Expression = {""}}
        }
    }
    #if it does not contains tags.
    else
    {
        $log | Select-Object EventTimeStamp, Caller, SubscriptionId,@{name="Operation"; Expression = {$_.operationname.LocalizedValue}}, @{name="tags"; Expression = {""}}
    }

    Write-Output "************************"
}

测试结果:

对于python,你可以看看this github issue,里面介绍了如何从azureactivity日志中获取日志,但是你需要研究一下如何添加标签到输出。

希望对您有所帮助。