Azure-Samples / virtual-machines-python-manage

An example illustrating how to use Python to manage your Azure Virtual Machines
MIT License
104 stars 84 forks source link

How to query using tags or read VM names, RG/ID from file #19

Closed eosho closed 5 years ago

eosho commented 6 years ago

I am not too versed with using Azure with python. I have searched online but can't find any resource to either query VMs using tags or using VM name, RG or ID to start/deallocate VMs. My main reason for wanting to using python was because the CLI folks told me python can handle wait periods to avoid Azure throttling.

Sample snippet

try:
    vmlist = open("vmlist.txt","r")

    for vm in vmlist.readlines():
        values = vm.split()
        if OPTION in ['stop', 'deallocate']:   
            # Stop the VM
            print('\nDeallocating the VM')
            async_vm_deallocate = compute_client.virtual_machines.deallocate(GROUP_NAME, VM_NAME)
            async_vm_deallocate.wait()

        elif OPTION in ['start']:
            # Start the VM
            print('\nStart VM')
            async_vm_start = compute_client.virtual_machines.start(GROUP_NAME, VM_NAME)
            async_vm_start.wait()

        else:
            print('\nDoing nothing. Select either start or stop")
            exit()

finally:
    vmlist.close()
lmazuel commented 6 years ago

Hi @Fumes007 Testing existence of a VM by his name, would be just do a "get" and catch any exception as meaning "does not exist". By tag, you must use the "azure-mgmt-resource" client, using the list ARM resources with a filter: https://docs.microsoft.com/en-us/python/api/azure-mgmt-resource/azure.mgmt.resource.resources.v2018_05_01.operations.resourcesoperations?view=azure-python#list

filter should look like (not tested, might need typo adjustements): tagname eq 'mytag' and resourceType eq 'Microsoft.Compute/virtualMachines'

lmazuel commented 5 years ago

Closing, answered and no activity.