Azure Python SDK solution to list VM names in subscription using Azure Cloud Shell

Here is a small snippet prepared to get VM list in an Azure subscription supported by Azure Python SDK. Hope, the code help you to develop similar code supports Azure Python SDK

Azure Cloud Shell has Python, PIP packages enabled by default

In-order to get the advantage of re-designed authentication mechanism, install azure-identity using PIP as below

pip install azure-identity

The code used for listing the VM names in the subscription is as follows:

from azure.common.credentials import ServicePrincipalCredentials
 from azure.mgmt.compute import ComputeManagementClient
    
 credential = ServicePrincipalCredentials(client_id='your sp client id',secret='your sp secret',tenant='your tenant id')
 compute_client = ComputeManagementClient(credential, 'your subscription id')
    
 # List all Virtual Machines in the specified subscription
 def list_virtual_machines():
     for vm in compute_client.virtual_machines.list_all():
         print(vm.name)
    
 list_virtual_machines()

This code ran with the following syntaxt

python3 vmlist.py

Tags:

No responses yet

Leave a Reply

Your email address will not be published.

Recent Comments
Add External Contacts in Microsoft Teams