Skip to content

Instantly share code, notes, and snippets.

@jadenlemmon
Created October 13, 2023 16:32
Show Gist options
  • Save jadenlemmon/043cced7d481033acba9e5f594bcb524 to your computer and use it in GitHub Desktop.
Save jadenlemmon/043cced7d481033acba9e5f594bcb524 to your computer and use it in GitHub Desktop.
GCP Idle VM Shutdown Script
#!/bin/bash
# Add this script to instance metadata and reboot
# gcloud compute instances add-metadata INSTANCE_NAME --metadata-from-file startup-script=gcp_idle_vm.sh
# To follow logs sudo journalctl -f -u google-startup-scripts.service
# For this to work ensure your vm is private or has appropriate firewall rules
# otherwise brute force attacks will keep your vm alive
has_connection_existed=false
idle_count=0
while true; do
is_ssh_connected=false
# This command won't work because vscode connections
# don't always show up here
# who -u | grep -q jaden && is_ssh_connected=true
# Check if there are any active SSH connections
ss -a -e | grep ssh | grep ESTAB && is_ssh_connected=true
echo "SSH connected: $is_ssh_connected"
if ! $is_ssh_connected; then
# If all ssh connections have been closed, shut down the VM
# Only after the first initial connection has been made
if $has_connection_existed; then
idle_count=$((idle_count + 1))
echo "SSH connections have been idle for $idle_count minutes"
if [ $idle_count -gt 5 ]; then
echo "SSH connections have been idle for 5 minutes. Shutting down..."
sudo poweroff
fi
else
echo "No SSH connection has been made yet. Waiting..."
fi
else
has_connection_existed=true
idle_count=0
echo "SSH sessions are active. Waiting..."
fi
sleep 60
done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment