有没有办法找出给定 VM 的资源组,然后使用 Python sdk 在 Azure 中找出 VM 的详细信息

Is there a way to find out Resource group for a given VM and then find out details of VM in Azure using Python sdk

我在这里参考了各种文章,但没有找到确切的解决方案

有没有办法找出给定 VM 的资源组,然后使用 Python sdk

找出 Azure 中 VM 的详细信息

谁能告诉我正确的例子?

我想做的是

如果您只知道虚拟机的名称,唯一的方法是通过 list_all() 方法列出所有虚拟机 -> 然后通过名称选择指定的虚拟机。

注意:这里的风险是,vm 的名称在不同的资源组中不是唯一的。所以有可能在不同的资源组中存在多个相同的vm。你应该处理这个案子。

示例代码:

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

SUBSCRIPTION_ID = 'xxxx'
VM_NAME = 'xxxx'

credentials = ServicePrincipalCredentials(
    client_id='xxxxx',
    secret='xxxxx',
    tenant='xxxxx'
)

compute_client = ComputeManagementClient(
    credentials=credentials,
    subscription_id=SUBSCRIPTION_ID
)

vms = compute_client.virtual_machines.list_all()

myvm_resource_group=""

for vm in vms:
    if vm.name == VM_NAME:
        print(vm.id)

        #the vm.id is always in this format: 
        #'/subscriptions/your_subscription_id/resourceGroups/your_resource_group/providers/Microsoft.Compute/virtualMachines/your_vm_name'
        #so you can split it into list, and the resource_group_name's index is always 4 in this list.
        temp_id_list=vm.id.split('/')
        myvm_resource_group=temp_id_list[4]

print("**********************!!!!!!!!!!")

print("the vm test0's resource group is: " + myvm_resource_group)

# now you know the vm name and it's resourcegroup, you can use other methods,
# like compute_client.virtual_machines.get(resource_group_name, vm_name) to do any operations for this vm.

如果您还有其他问题,请告诉我。