使用 Python API 在 Azure 上获取虚拟机创建时间

Get virtual machine created time on Azure using Python API

我的要求是让订阅中的所有 VM 都有启动(创建)时间。我没有在仪表板中找到 VM 创建时间,而在 Activity log 中找到了时间戳。我想获取由一个订阅 ID 创建的所有 VM 以及创建时间。

(为此帐户详细信息启用了 2FA,因此 - UserPassCredentials 将不起作用)

订阅 ID 中所有 VM 的列表:

import os
from azure.common.credentials import ServicePrincipalCredentials
from azure.mgmt.compute import ComputeManagementClient
subscription_id = os.environ['AZURE_SUBSCRIPTION_ID']
credentials = ServicePrincipalCredentials(client_id=os.environ['AZURE_CLIENT_ID'], secret=os.environ['AZURE_CLIENT_SECRET'], tenant=os.environ['AZURE_TENANT_ID'])
compute_client = ComputeManagementClient(credentials, subscription_id)
for vm in compute_client.virtual_machines.list_all():
    print("\tVM: {}".format(vm.name)) 

Activity log获取创建时间:

import os
import datetime
from pprint import pprint
from azure.monitor import MonitorClient
from azure.common.credentials import ServicePrincipalCredentials

today = datetime.datetime.now().date()
filter = " and ".join([ "eventTimestamp le '{}T00:00:00Z'".format(today), "resourceGroupName eq 'test-group'" ])
subscription_id = 'xxxxx'
credentials = ServicePrincipalCredentials(client_id=os.environ['AZURE_CLIENT_ID'], secret=os.environ['AZURE_CLIENT_SECRET'], tenant=os.environ['AZURE_TENANT_ID'])
client = MonitorClient(credentials, subscription_id)
select = ",".join([ "Administrative", "Write VirtualMachines" ]) 
activity_logs = client.activity_logs.list( filter=filter, select=select )

for i in activity_logs:
    pprint(i.__dict__) 

我能够获取所有 VM(第一个示例程序),但是在尝试获取 Activity log 时遇到一些错误(第二个示例程序)。

错误:

    Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/Library/Python/2.7/site-packages/msrest/paging.py", line 109, in __next__
    self.advance_page()
  File "/Library/Python/2.7/site-packages/msrest/paging.py", line 95, in advance_page
    self._response = self._get_next(self.next_link)
  File "/Library/Python/2.7/site-packages/azure/monitor/operations/activity_logs_operations.py", line 117, in internal_paging
    raise models.ErrorResponseException(self._deserialize, response)
azure.monitor.models.error_response.ErrorResponseException: Operation returned an invalid status code 'Bad Request'

有人可以帮我找到问题吗?非常感谢任何帮助。

根据文档,您的日期似乎应该被转义。此外,他们似乎需要一个日期时间(而不是日期): https://docs.microsoft.com/en-us/rest/api/monitor/activitylogs

filter = " and ".join([
        "eventTimestamp le '{}T00:00:00Z'".format(today),
        "resourceGroupName eq 'test-group'"
])

我今天尝试使用您提供的代码获取我的资源组活动日志,我重现了您的问题。

我的代码:

import os
import datetime
from pprint import pprint
from azure.monitor import MonitorClient
from azure.common.credentials import ServicePrincipalCredentials

subscription_id = '***'
client_id='***'
secret='***'
tenant='***'

today = datetime.datetime.now().date()
filter = " and ".join([ "eventTimestamp le '{}T00:00:00Z'".format(today), "resourceGroupName eq 'jay'" ])

credentials = ServicePrincipalCredentials(client_id=client_id, secret=secret, tenant=tenant)

client = MonitorClient(credentials, subscription_id)
select = ",".join([ "eventName", "operationName" ])

print select
print filter
activity_logs = client.activity_logs.list( filter=filter, select=select )

for log in activity_logs:
    # assert isinstance(log, azure.monitor.models.EventData)
    print(" ".join([
        log.event_name.localized_value,
        log.operation_name.localized_value
    ]))

运行 结果:

eventName,operationName
eventTimestamp le '2017-10-17T00:00:00Z' and resourceGroupName eq 'jay'
Traceback (most recent call last):
  File "E:/PythonWorkSpace/ActiveLog/FetchActiveLog.py", line 24, in <module>
    for log in activity_logs:
  File "E:\Python27\lib\site-packages\msrest\paging.py", line 109, in __next__
    self.advance_page()
  File "E:\Python27\lib\site-packages\msrest\paging.py", line 95, in advance_page
    self._response = self._get_next(self.next_link)
  File "E:\Python27\lib\site-packages\azure\monitor\operations\activity_logs_operations.py", line 117, in internal_paging
    raise models.ErrorResponseException(self._deserialize, response)
azure.monitor.models.error_response.ErrorResponseException: Operation returned an invalid status code 'Bad Request'

研究 Azure Monitor Python SDK 后,我发现了不同之处。

filter = " and ".join([ "eventTimestamp ge '{}T00:00:00Z'".format(today), "resourceGroupName eq 'jay'" ])

这里是ge,不是le

我修改了关键字,然后代码对我来说效果很好。

eventName,operationName
eventTimestamp ge '2017-10-17T00:00:00Z' and resourceGroupName eq 'jay'
End request Microsoft.Compute/virtualMachines/delete
End request Microsoft.Compute/virtualMachines/delete
End request Microsoft.Compute/virtualMachines/delete
Begin request Microsoft.Compute/virtualMachines/delete
End request Microsoft.Compute/virtualMachines/deallocate/action
End request Microsoft.Compute/virtualMachines/deallocate/action
Begin request Microsoft.Compute/virtualMachines/deallocate/action
End request Microsoft.Compute/virtualMachines/write
End request Microsoft.Compute/disks/write
End request Microsoft.Compute/virtualMachines/write
End request Microsoft.Network/networkSecurityGroups/write
End request Microsoft.Network/networkInterfaces/write
End request Microsoft.Network/publicIPAddresses/write

希望对你有帮助。