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



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

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

它工作正常,我也已经拿到了令牌

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

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

如何筛选一个 VM 并将所有 VM 相关信息输出到 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}")        

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

文档

最新更新