如何查询Azure虚拟机创建记录

    最近收到个需求,想看一下Azure虚拟机创建的记录,详细了解最近云上都有什么新增的资源,这其实也是个比较正常的需求,随着云的使用越来越广泛,很多企业早已不满足于简单的用云,而是更聚焦在如何把云用好上,更核心的一点是越来越多的企业开始关注云上的cost问题,因此资源使用的合理性越来越是企业关注的一个重点


    回归主题,那么如何在Azure实现这个需求呢,其实在资源组的deployment记录中是可以找到VM的创建记录的,但是这种方式收集到的信息很零散,我们也不可能每个资源组都去一个个查看,整理这些信息,那么有什么好的办法呢?

1.png




    其实我们可以直接通过Azure的PowerShell解决这个问题,只需要编写一个简单的脚本就可以了,首先运行以下命令,获取到Azure近三个月的所有log

    

$logs = Get-AzureRmLog -ResourceProvider Microsoft.Compute -StartTime (Get-Date).AddDays(-90) -Maxrecord 100000


2.png

foreach($log in $logs)
{
    if(($log.OperationName.Value -eq 'Microsoft.Compute/virtualMachines/write') -and ($log.SubStatus.Value -eq 'Created'))
    {
        Write-Output "$($log.caller) created vm $($log.Id.split("/")[8])  at $($log.EventTimestamp)  in Resource Group $($log.ResourceGroupName)"
    }

}

    



这样就能看到VM创建的记录了!

3.png



那么如果想把这些信息汇总到Excel里呢?可以通过以下的代码即可!

[pscustomobject[]]$VMObjects = $null
foreach ($log in $logs) {
        if (($log.OperationName.Value -eq 'Microsoft.Compute/virtualMachines/write') -and ($log.SubStatus.Value -eq 'Created')) {
            Write-Output "$($log.caller) created vm $($log.Id.split("/")[8])  at $($log.EventTimestamp)  in Resource Group $($log.ResourceGroupName)"

            $VMObject = New-Object -TypeName psobject
            $VMObject | Add-Member -MemberType NoteProperty -Name SubscriptionName -Value $SubscriptionName
            $VMObject | Add-Member -MemberType NoteProperty -Name SubscriptionID -Value $SubscriptionID
            $VMObject | Add-Member -MemberType NoteProperty -Name ResourceGroup -Value $log.ResourceGroupName
            $VMObject | Add-Member -MemberType NoteProperty -Name VMName -Value $log.Id.split("/")[8]
            $VMObject | Add-Member -MemberType NoteProperty -Name Time -Value $log.EventTimestamp
            $VMObjects += $VMObject

        }

    }
    
    $OutputPath="C:\vm.csv"
    $VMObjects | Export-Csv -NoTypeInformation -LiteralPath $OutputPath


最后要说的是,这种方法只能收集到90天以内的日志,因为Azure平台开放给用户的最长时间的log就是90天

猜你喜欢

转载自blog.51cto.com/mxyit/2467567