asp
asp

Reputation: 855

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

Upvotes: 1

Views: 1279

Answers (1)

Ivan Glasenberg
Ivan Glasenberg

Reputation: 30025

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.

Upvotes: 2

Related Questions