stop-idle-azure.py

Automatically Shutting Down and Deallocating an AZURE VM (when idle AND no one is logged in via SSH)

2

Votes

# This is how the cron file should look like. 

# PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games:/sn$
# * * * * * /home/script/stop-idle-azure.py > /tmp/user_error.log


## Watchout, for some reason cron files seem to require an extra new line at the end, 
## consult this SO: https://askubuntu.com/questions/23009/why-crontab-scripts-are-not-working
## Also take care to setup a PATH variable for the cron explicitly. It doesn't see 
## your regular PATH variable. 

# ---- 

# Here is the code for stop-idle-azure.py

#!/usr/bin/env python

# make sure these commands run and do the proper thing. 
# You might need to install azure cli: 
# "sudo apt install azure-cli " in ubuntu. 

# netstat -tnpa | grep 'ESTABLISHED.*sshd'
# az vm deallocate --name "myvmname" --resource-group "myvmresourcegroup"

import re
import subprocess
import psutil

THRESH         = 75.0
NAME           = "EDIT THIS WITH PROPER VALUES"
RESOURCE_GROUP = "EDIT THIS WITH PROPER VALUES"

def get_logged_in():
    shellout  = subprocess.Popen(['sudo', 'netstat', '-tnpa'],  stdout=subprocess.PIPE)
    shellout2 = subprocess.Popen(['grep', 'ESTABLISHED.*sshd'], stdin=shellout.stdout, stdout=subprocess.PIPE)
    outlist = list(shellout2.stdout)
    return len(outlist) == 0

def get_cpu_percent():
    f = open("/proc/loadavg", "r")
    cpu_list = f.readline().split()
    cpu_percent = float(cpu_list[1])
    return cpu_percent

def main():
    # check to make sure there are no active
    # ssh connections, meaning no humans
    # are working on the machine,
    # then go ahead and check
    # the cpu usage in percent, if it falls
    # below some threshold, send the command
    # to shutdown the vm and deallocate it.


    logged_in   = get_logged_in()
    cpu_percent = get_cpu_percent()
    print ("cpu_percent: ", cpu_percent)

    if logged_in:
        if cpu_percent < THRESH:
            print ("no one logged in, and vm is idle, stopping and deallocating.. ")
            subprocess.run(['az', 'vm', 'deallocate', "--name", NAME, "--resource-group", RESOURCE_GROUP])
        else:
            print("no one logged in, but vm is busy. leaving it alone..")
    else:
        print ("someone is logged in, leaving the vm alone.. ")

if __name__ == '__main__':
    main()

Vote Here

You must earn at least 1 vote on your snippets to be allowed to vote

Terms Of Use

Privacy Policy

Featured snippets are MIT license

Gears & Masters

Advertise

DevOpsnipp.com © 2020

medium.png