如何使用 Python 仅列出 1 个 Azure 虚拟机的详细信息?

How could I list details of only 1 Azure Virtual Machines using Python?

我已使用以下代码从我的 Azure 帐户获取访问令牌。

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

很好用,我也拿到了token

但是当我使用下面的语句时,它列出了所有虚拟机的信息,但我只需要一个虚拟机 我参考了文档,但它没有任何过滤示例

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()

如何过滤一个虚拟机并将所有虚拟机相关信息输出到json

您可以像这样使用get方法(首选):

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

但是,如果你想用 list_all() 来做,你可以这样做:

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}")        

您可以参考文档和示例 link 以查看其他可用属性。

Example

Docs