Search code examples
pythonazureazure-sdk-python

Azure python SDK - Remove or deallocate VM from resource group


I want to deallocate a VM from a resource group using Azure sdk for python. I have already created a VM using the sdk (compute_client.virtual_machines.create_or_update) but i am unable to find any specific method which would stop or deallocate a VM.

Thank You


Solution

  • You can refer to the doc of Azure SDK for Python and find the method deallocate of VirtualMachinesOperations, please see http://azure-sdk-for-python.readthedocs.org/en/latest/ref/azure.mgmt.compute.operations.html#azure.mgmt.compute.operations.VirtualMachinesOperations.deallocate.

    Here is code as reference.

    from azure.common.credentials import ServicePrincipalCredentials
    from azure.mgmt.compute import ComputeManagementClient, ComputeManagementClientConfiguration
    
    credentials = ServicePrincipalCredentials(
        client_id = '<client-id>',
        secret = '<key>',
        tenant = '<tenant-id>'
    )
    
    subscription_id = '<subscription-id>'
    
    compute_config = ComputeManagementClientConfiguration(credentials, subscription_id, api_version='2015-05-01-preview')
    compute_client = ComputeManagementClient(compute_config)
    resource_group_name = '<resource-group>'
    vm_name = '<vm-name>'
    result = compute_client.virtual_machines.deallocate(resource_group_name, vm_name)