Share this post on:


As we know, Azure vm bill can be expensive, and we want to use resources only when we need them. In order to stop being billed for the vm, we have to stop it and de-allocate it in the Azure portal; shutting down vm itself doesn’t stop Microsoft from billing us.

I wrote a simple python script that turns on and off vm directly from CLI / command prompt.


import json, requests, sys
import sys

Subscription_Id = "SubscriptionID"
Tenant_Id = "TenantID"
Client_Id = "ClientID"
Secret = "password"
resourceGroups = "myResourceGroup"

data = {"grant_type": "client_credentials",
"client_id": Client_Id,
"client_secret": Secret,
"resource": ""}

API_AZURE = "{}/oauth2/token".format(Tenant_Id)
get_token = url=API_AZURE, data=data).json()['access_token']

def vm_control(*args):
    if len(sys.argv) == 3:
        vmName = sys.argv[1]
        if sys.argv[2] == "on":
            print("Powering on {}!".format(vmName))
            power_on = "{}/resourceGroups/{" \
                Subscription_Id, resourceGroups, vmName)
            switch_on =,headers={'Authorization': 'Bearer {}'.format(get_token)})
            if switch_on.status_code !=
                print("Success, API code: " + str(switch_on.status_code))
                print("Failure, API code: " + str(switch_on.status_code))
        elif sys.argv[2] == "off":
            print("Powering off {}!".format(vmName))
            power_off = "{}/resourceGroups/{" \
                Subscription_Id, resourceGroups, vmName)
            switch_off =, headers={'Authorization': 'Bearer {}'.format(get_token)})
            if switch_off.status_code !=
                print("Success, API code" + str(switch_off.status_code))
                print("Failure, API code " + str(switch_off.status_code))
            print("Unknown argument!")
        print("Incorrect number of arguments! Usage: VM name + on/off ")

if __name__ == '__main__':


Open the terminal, cd into the python script location and provide 2 positional arguments: ‘vm_name + on/off’:

pawel@pawel-HP-EliteBook-820-G3:~/PycharmProjects/pythonProject$ ./ eve-ng-lab on
Powering on eve-ng-lab!
Success 202

Leave a Comment

Your email address will not be published. Required fields are marked *