skip to Main Content

I have to use API or python package which will provide me information of all Azure vm instances
means all instance types those are present in the azure.

First, installed the Azure Python SDK using pip:

pip install azure-sdk

Next, import the necessary modules and authenticate with Azure:

import os
from azure.common.credentials import ServicePrincipalCredentials
from azure.mgmt.compute import ComputeManagementClient
subscription_id = 'my-subscription-id'

client_id = 'my-client-id' client_secret = ‘my-client-secret’ tenant_id = ‘my-tenant-id’`

credentials = ServicePrincipalCredentials( client_id=client_id, secret=client_secret, tenant=tenant_id )
vm_list = compute_client.virtual_machines.list_all()

for vm in vm_list:
print(vm.name)

Using above code, I could see only those instances which I have created in my subscription ,
But I want All the instance types and its information using any API or python package.

2

Answers


  1. If you want to get all Azure Virtual Machines, you should probably use the Resource Graph.

    https://learn.microsoft.com/en-us/azure/governance/resource-graph/first-query-python#run-your-first-resource-graph-query

    It will allow you to get all instances, for any subscription your service principal has access.

    The Resource Graph request should be something like
    Resources | where type =~ ‘microsoft.compute/virtualmachines’

    Login or Signup to reply.
  2. I tried in my environment and got below results:

    I tried in PowerShell to get list of all virtual machine Instance across all subscription.

    Command:

    $Subscriptions = Get-AzSubscription 
    foreach ($sub in $Subscriptions) 
    {
    Get-AzSubscription -SubscriptionName $sub.Name | Set-AzContext 
    az account set -s $sub.Name     
    write-host "subscriptionname :" $sub.Name  
    write-host " " 
    $vmlist=Get-AzVM 
    $vmlist
    }
    

    Console:
    enter image description here

    If you need specific view (virtual machine name or any other properties) of azure virtual machine, you can use below command.

    Command:

    $Subscriptions = Get-AzSubscription 
    foreach ($sub in $Subscriptions) 
    {
    Get-AzSubscription -SubscriptionName $sub.Name | Set-AzContext 
    az account set -s $sub.Name     
    write-host "subscriptionname :" $sub.Name   
    write-host " "
    $vmlist=Get-AzVM 
    write-host "Vm  from  subscription " $sub.Name 
    
    foreach ($vm in $vmlist) 
    {
    write-host "vm name :   " $vm.name
    }
    write-host " " 
    }
    

    Console:
    enter image description here

    If you need to call PowerShell script from python you can refer this link by Jamie.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search