简体   繁体   中英

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

I refereed to various articles here,but not found exact solution

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

can some one point me to right example?

What I am trying to do is

  • input private ip of azure vm
  • need to find out resource group in which this azure machine
  • then it should get vm details of above vm under that resource management group

If you just know the name of the vm, the only way is that list all the vms via list_all() method -> then pick up the specified vm via it's name.

Note: the risk here is that, the vm's name is not unique across different resource groups. So it's possible that there're more than one vm with the same same in different resource groups. You should take care of this case.

The sample code:

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.

Please let me know if you still have more issues.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM