-2

I am trying to list Azure VMs using python code. could someone help me with this issue?

I have already tried to go through the code on the Microsoft website but it is not clear to me.

Khalid
  • 1
  • 1
  • 1
    Hello Khalid and welcome to Stack Overflow! This is not a very good question for this site, we're about fixing broken code, not so much about helping you read the documentation. Here is a handy post that can help you ask better questions in the future here: https://stackoverflow.com/help/how-to-ask – Hoog Jul 12 '19 at 17:59
  • Hello Hoog, Thank you for the welcoming and the feedback. I am here to learn and I will get better on how to ask a question. Thanks again for your comment :) – Khalid Jul 31 '19 at 18:11
  • Does this answer your question? [How could I list Azure Virtual Machines using Python?](https://stackoverflow.com/questions/58925397/how-could-i-list-azure-virtual-machines-using-python) – Alon Lavian Jun 01 '22 at 17:53

1 Answers1

2

First, you need to follow the section Register your client application with Azure AD of Azure offical document Azure REST API Reference to register an application with Azure AD on Azure portal for getting the required parameters client_id and secret for Authentication to list VMs.

And, you continue to get the other required parameters subscription_id and tenant_id.

Then, to create a virtual environment in Python to install Azure SDK for Python via pip install azure or just install Azure Compute Management for Python via pip install azure-mgmt-compute.

Here is my sample code.

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

credentials = ServicePrincipalCredentials(
    client_id='<your client id>',
    secret='<your client secret>',
    tenant='<your tenant id>'
)

subscription_id = '<your subscription id>'
client = ComputeManagementClient(credentials, subscription_id)

If just list VMs by resource group, to use function list(resource_group_name, custom_headers=None, raw=False, **operation_config) as the code below.

resource_group_name = '<your resource group name>'
vms_by_resource_group = client.virtual_machines.list(resource_group_name)

Or you want to list all VMs in your subscription, to use function list_all(custom_headers=None, raw=False, **operation_config) as the code below.

all_vms = client.virtual_machines.list_all()

As references, there are two SO threads I think which may help for understanding deeper: How to get list of Azure VMs (non-classic/Resource Managed) using Java API and Is it anyway to get ftpsState of azure web app (Azure Function app) using Python SDK?.

Hope it helps.

Peter Pan
  • 23,476
  • 4
  • 25
  • 43