1

I’ve used the below code to get the Access Token from my Azure account.

https://github.com/AzureAD/azure-activedirectory-library-for-python/blob/dev/sample/certificate_credentials_sample.py

It’s working fine, I already got the token as well

But when I use below statement, its listing all VM's information, but I need only for one VM I referred to documentation, but it does not have any example for filtering

from azure.mgmt.compute import ComputeManagementClient
from azure.common.credentials import ServicePrincipalCredentials


Subscription_Id = "xxxxx"
Tenant_Id = "xxxxx"
Client_Id = "xxxxx"
Secret = "xxxxx"

credential = ServicePrincipalCredentials(
        client_id=Client_Id,
        secret=Secret,
        tenant=Tenant_Id
        )

compute_client = ComputeManagementClient(credential, Subscription_Id)

vm_list = compute_client.virtual_machines.list_all()

How to filter one VM and to output of all vm related info to json

asp
  • 777
  • 3
  • 14
  • 33

1 Answers1

2

You can use the get method like this (preferred):

vm = compute_client.virtual_machines.get(GROUP_NAME, VM_NAME, expand='instanceView')

But, if you wanted to do it with list_all(), you could do something like this:

vm_list = compute_client.virtual_machines.list_all()

filtered = [vm for vm in vm_list if vm.name == "YOUR_VM_NAME"] #All VMs that match

vm = filtered[0] #First VM

print(f"vm size: {vm.hardware_profile.vm_size}")        

You can refer to the docs and example link to see other properties available.

Example

Docs

Rithin Chalumuri
  • 1,739
  • 7
  • 19
  • hi is there way to know which resource group my vm belongs to ? – asp Jul 08 '20 at 14:28
  • 1
    you can view the resource group in azure portal; all resources and you would just need the name of the resource group for the python code. If you want to do it with code, you may need to use `compute_client.virtual_machines.list_all()` method and then manually filter out for the VM name your looking for then you can access information about it; updated an example in this answer with list all. – Rithin Chalumuri Jul 08 '20 at 20:18