Skip to content

Instantly share code, notes, and snippets.

@vpack
Created July 4, 2019 20:21
Show Gist options
  • Save vpack/e5fb905620800c37b8b1e943c26f7004 to your computer and use it in GitHub Desktop.
Save vpack/e5fb905620800c37b8b1e943c26f7004 to your computer and use it in GitHub Desktop.
Shutdown AWS host on timer

On several occations, I have spin up my test host in AWS and left if running for months without using it. I wanted this instance to shutdown on timer. I can always start it up anytime - that does not bother me.

Here is sample code;

[root@ip-172-30-0-62 ~]# crontab -l
* * * * * date >> /var/log/cron-date
* * * * * /root/shutdown-timer >> /var/log/shutdown.log 2>&1
[root@ip-172-30-0-62 ~]# cat shutdown-timer
#!/usr/bin/python

import os, sys
import time
from datetime import timedelta

SHUTDOWN_AFTER = int(sys.argv[1]) if len(sys.argv) > 1 else 55 # minutes

with open('/proc/uptime', 'r') as f:
    uptime_seconds = float(f.readline().split()[0])
    uptime_string = str(timedelta(seconds = uptime_seconds))
    print( "Date: %s - Uptime: %s" % ( time.strftime("%Y.%m.%d"), uptime_string) )
    if (uptime_seconds > SHUTDOWN_AFTER * 60) :
       print( "Shutting down.. at %s" % uptime_string )
       os.system("/sbin/shutdown now -h")
       
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment