最近收到个需求,想看一下Azure虚拟机建立的记录,详细了解最近云上都有什么新增的资源,这其实也是个比较正常的需求,随着云的使用愈来愈普遍,不少企业早已不知足于简单的用云,而是更聚焦在如何把云用好上,更核心的一点是愈来愈多的企业开始关注云上的cost问题,所以资源使用的合理性愈来愈是企业关注的一个重点
ide
回归主题,那么如何在Azure实现这个需求呢,其实在资源组的deployment记录中是能够找到VM的建立记录的,可是这种方式收集到的信息很零散,咱们也不可能每一个资源组都去一个个查看,整理这些信息,那么有什么好的办法呢?
3d
其实咱们能够直接经过Azure的PowerShell解决这个问题,只须要编写一个简单的脚本就能够了,首先运行如下命令,获取到Azure近三个月的全部log日志
$logs = Get-AzureRmLog -ResourceProvider Microsoft.Compute -StartTime (Get-Date).AddDays(-90) -Maxrecord 100000
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建立的记录了!orm
那么若是想把这些信息汇总到Excel里呢?能够经过如下的代码便可!
blog
[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天ip