azureazure-virtual-machine

Azure Virtual Machine - Programmatically Start / Stop Machine


I've tried to reference this as best I can, but I can't seem to find anything immediately obvious in either Azure SDK documentation or various examples in their repositories.

Essentially, I would like to be able to programmatically start / stop an Azure VM, perhaps from a simple Python script or Go lang ... does anyone know if this is this possible with any of the APIs in their SDK?

If yes, where could I find any references to achieve this?


Solution

  • Azure Virtual Machine - Programatically Start / Stop Machine

    Prerequistes

     pip install azure.mgmt.compute azure.identity
    

    Here is the Python code to stop/start the Azure VM

    from azure.identity import DefaultAzureCredential
    from azure.mgmt.compute import ComputeManagementClient
    from azure.mgmt.compute.models import VirtualMachine
    
    # Azure subscription ID
    subscription_id = 'subscription_id'
    
    # Resource group name and VM name
    resource_group_name = 'Venkat'
    vm_name = 'venkat-vm'
    
    # Initialize Azure credentials
    credential = DefaultAzureCredential()
    
    # Initialize ComputeManagementClient
    compute_client = ComputeManagementClient(credential, subscription_id)
    
    # Stop the VM
    async_vm_stop = compute_client.virtual_machines.begin_power_off(resource_group_name, vm_name)
    async_vm_stop.wait()
    
    print(f"The VM {vm_name} has been stopped.")
    

    Start the VM

    async_vm_start = compute_client.virtual_machines.begin_start(resource_group_name, vm_name)
    async_vm_start.wait()
    
    print(f"The VM {vm_name} has been started.")
    

    After running the code, the virtual machine has successfully stopped.

    enter image description here

    enter image description here