Share this post on:

Introduction

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.

Script

#!/usr/bin/python3
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": "https://management.azure.com"}


API_AZURE = "https://login.microsoftonline.com/{}/oauth2/token".format(Tenant_Id)
get_token = requests.post( 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 = "https://management.azure.com/subscriptions/{}/resourceGroups/{" \
                       "}/providers/Microsoft.Compute/virtualMachines/{}/start?api-version=2020-06-01".format(
                Subscription_Id, resourceGroups, vmName)
            switch_on = requests.post(url=power_on,headers={'Authorization': 'Bearer {}'.format(get_token)})
            if switch_on.status_code != requests.codes.ok:
                print("Success, API code: " + str(switch_on.status_code))
            else:
                print("Failure, API code: " + str(switch_on.status_code))
        elif sys.argv[2] == "off":
            print("Powering off {}!".format(vmName))
            power_off = "https://management.azure.com/subscriptions/{}/resourceGroups/{" \
                        "}/providers/Microsoft.Compute/virtualMachines/{}/deallocate?api-version=2020-06-01".format(
                Subscription_Id, resourceGroups, vmName)
            switch_off = requests.post(url=power_off, headers={'Authorization': 'Bearer {}'.format(get_token)})
            if switch_off.status_code != requests.codes.ok:
                print("Success, API code" + str(switch_off.status_code))
            else:
                print("Failure, API code " + str(switch_off.status_code))
        else:
            print("Unknown argument!")
    else:
        print("Incorrect number of arguments! Usage: VM name + on/off ")


if __name__ == '__main__':
    vm_control(*sys.argv)

Usage

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$ ./main.py 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 *