DEV Community

Chris Wendt
Chris Wendt

Posted on • Edited on

How to auto-shutdown GCP VMs and save $

The following script will shut down an instance that hasn't had any SSH connections in a while. The debounce defaults to 300 seconds.

  1. Copy these files into your VM:

/usr/bin/auto-shutdown.py:

#!/usr/bin/env python3

import json
import math
import os
import subprocess
from pathlib import Path
import time
from datetime import datetime

def main():
    timeout = int(os.environ.get("IDLE_TIMEOUT", "600"))
    interval = 60

    idle_since = getBootTime()

    while True:
        out = subprocess.check_output("last -F | jc --last", shell=True)
        for user in json.loads(out):
            if user.get("logout", None) == "still logged in":
                idle_since = max(idle_since, datetime.now().timestamp())
            elif "logout_epoch" in user:
                idle_since = max(idle_since, user["logout_epoch"])

        idle = round(datetime.now().timestamp() - idle_since)
        if idle > timeout:
            print(f"Idle for {idle}s, shutting down...")
            subprocess.check_call("shutdown now", shell=True)
        else:
            print(f"Idle for {idle}s, checking again in {interval}s...")
            time.sleep(interval)


def getBootTime():
    uptime = float(Path("/proc/uptime").read_text().split()[0])
    return datetime.now().timestamp() - uptime


if __name__ == "__main__":
    main()
Enter fullscreen mode Exit fullscreen mode

/etc/systemd/system/auto-shutdown.service:

[Unit]
Description=Auto-shutdown VM

[Service]
ExecStart=/usr/bin/auto-shutdown.py
Restart=always
Environment=PYTHONUNBUFFERED=true

[Install]
WantedBy=multi-user.target
Enter fullscreen mode Exit fullscreen mode
  1. pip3 install jc and if which jc shows conda, then sudo ln -sf /opt/conda/bin/jc /usr/bin/jc
  2. sudo chmod u+x /usr/bin/auto-shutdown.py
  3. sudo systemctl daemon-reload
  4. sudo systemctl enable auto-shutdown.service
  5. sudo systemctl restart auto-shutdown
  6. systemctl status auto-shutdown.service

Inspiration.

Top comments (0)