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

3
  • 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: stackoverflow.com/help/how-to-ask Commented Jul 12, 2019 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 :) Commented Jul 31, 2019 at 18:11
  • Does this answer your question? How could I list Azure Virtual Machines using Python? Commented Jun 1, 2022 at 17:53

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you so much. That was very helpful.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.