3

My requirement is to get all VMs in a subscription with launch(created) time. I didn't find the VM created time in the dashboard where as in the Activity log found a timestamp. I would like to fetch all VMs which were created by one subscription id along with created time.

(For this account details 2FA is enabled so - UserPassCredentials won't work )

List of all VMs in a subscription id:

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)) 

Fetch created time from 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__) 

I'm able to get the all VMs(1st sample program), However while trying to fetch the Activity log get some error(2nd sample program).

Error:

    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'

Can somebody help me to find the issue please? any help really appreciated.

user6136315
  • 695
  • 4
  • 13
  • 37

3 Answers3

1

I tried to fetch my active log of resource group today by using the code you provided and I reproduce your issue.

My code:

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
    ]))

Running result:

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'

After rearching the Azure Monitor Python SDK, I found the difference.

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

Here is ge ,not le.

I modify the keyword then the code works well for me.

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

Hope it helps you.

Jay Gong
  • 23,163
  • 2
  • 27
  • 32
0

Based on the doc, it seems your date should be escaped. Moreover, seems they take a datetime (and not a date): https://learn.microsoft.com/en-us/rest/api/monitor/activitylogs

filter = " and ".join([
        "eventTimestamp le '{}T00:00:00Z'".format(today),
        "resourceGroupName eq 'test-group'"
])
Laurent Mazuel
  • 3,422
  • 13
  • 27
  • I just updated the code what you proposed, seems like issue still persists. I've tried to list all attributes in the activity_log. no luck. – user6136315 Oct 16 '17 at 22:28
0

Call az cli from python use below command

az vm list 

This will list json data with fields and you can filter

date = vm['timeCreated']

//"timeCreated": "2022-06-24T14:13:00.326985+00:00",

Aditya Malviya
  • 1,907
  • 1
  • 20
  • 25