【问题标题】:How could I list details of only 1 Azure Virtual Machines using Python?如何使用 Python 列出仅 1 个 Azure 虚拟机的详细信息?
【发布时间】:2020-10-22 17:59:49
【问题描述】:

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

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

很好用,我也拿到了令牌

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

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(<resource group>, <vm name>)
  • 您对想要获取的 VM 了解多少?
  • 我需要了解给定单个虚拟机的标签、磁盘、存储大小等

标签: python azure sdk virtual-machine


【解决方案1】:

您可以像这样使用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}")        

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

Example

Docs

【讨论】:

  • 嗨,有没有办法知道我的虚拟机属于哪个资源组?
  • 可以在azure portal中查看资源组;所有资源,您只需要 python 代码的资源组的名称。如果你想用代码来做,你可能需要使用compute_client.virtual_machines.list_all()方法,然后手动过滤掉你要找的VM名称,然后你就可以访问它的信息;用 list all 更新了这个答案中的一个例子。
猜你喜欢
  • 2021-06-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-10-19
  • 2019-12-15
  • 1970-01-01
相关资源
最近更新 更多