Skip to content

Instantly share code, notes, and snippets.

@jns
Last active February 11, 2022 15:47
Show Gist options
  • Save jns/464273152710a4c93b3655bd65298551 to your computer and use it in GitHub Desktop.
Save jns/464273152710a4c93b3655bd65298551 to your computer and use it in GitHub Desktop.
Bash script that stops an ec2 instance after 12 consecutive invocations without established ssh connection or screens
#!/bin/bash
# This script will check for the absence of any logged in user for 12 consecutive
# invocations. If the no user has logged in for 12 consecutive invocations then
# the EC2 instance will stop or hibernate depending on its configuration
# The ec2 instance profile must have permission to stop an ec2 instance.
#
# Copy this script to /usr/local/bin and make it executable
# Then add the following line to your crontab.
#
# */5 * * * * /usr/local/bin/stop-if-idle
#
# The script will be invoked every 5 minutes and will stop or hibernate the instance
# after the 12th invocation (1hr). To change the duration, change the frequency of
# the cron job. For instance, changing the cron to invoke every 10 minutes will
# stop or hibernate after 2hrs.
# Write the current number of ssh connections and screens to login_log
if [ ! -d /var/log/stop-if-idle ]; then mkdir /var/log/stop-if-idle; fi
login_log=/var/log/stop-if-idle/w.log
logins=`w -h | wc -l`
screens=`ls /var/run/screen | wc -l`
vscode=`ps -ef | grep vscode | grep -v grep | wc -l`
echo $((logins + screens + vscode)) >> $login_log
# Prepopulate a 12 element array with 1's.
# Then write the contents of login_log over the array
logins=(1 1 1 1 1 1 1 1 1 1 1 1)
i=0
for val in `tail -12 $login_log`; do
logins[$i]=$val
i=$i+1
done
# Compute the number of logins in the last 12 invocations
login_duty_cycle=0
for val in ${logins[@]}; do
((login_duty_cycle += $val))
done
# If the number of logins for 12 consecutive invocations is 0 then stop/hibernate
# Remove the login_log upon success so that the script starts over upon resume
if [ $login_duty_cycle -eq 0 ]; then
instance_id=`curl -s http://169.254.169.254/latest/meta-data/instance-id`
region=`curl -s http://169.254.169.254/latest/meta-data/placement/region`
hibernate_configured=`curl -d http://169.254.169.254/latest/meta-data/hibernation/configured`
if [ $hibernate_configured = 'true' ]; then hibernate='--hibernate'; fi
aws ec2 stop-instances --region $region --instance-ids $instance_id $hibernate && rm $login_log
fi;
@jns
Copy link
Author

jns commented Sep 8, 2021

Refined to check for vscode remote sessions

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment