温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

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

发布时间:2020-07-30 23:22:15 来源:网络 阅读:383 作者:mxy00000 栏目:云计算

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


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

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




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

    

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


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

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创建的记录了!

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



那么如果想把这些信息汇总到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天

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI