Last active
May 24, 2019 14:56
-
-
Save adamar/15ec9db7b07bc529f98ff3f1b3492f6e to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/bash | |
## Setup Lockfile | |
LOCKFILE=/tmp/lock.txt | |
if [ -e ${LOCKFILE} ] && kill -0 `cat ${LOCKFILE}`; then | |
echo "already running" | |
exit | |
fi | |
## Setup Trap | |
trap "rm -f ${LOCKFILE}; exit" INT TERM EXIT | |
echo $$ > ${LOCKFILE} | |
## Collect start time | |
START_TIME=$(date --date="$(uptime -s)" +"%s") | |
## Collect current time | |
NOW=$(date +"%s") | |
## Get uptime in secs | |
DIFF=$((NOW - START_TIME)) | |
## Check uptime more than an hour | |
if (( $DIFF > 3600 )); | |
then | |
if ! last | grep --silent "still logged in"; | |
then | |
## Get instance info | |
INSTANCE_ID=$(curl --silent http://169.254.169.254/latest/meta-data/instance-id) | |
EC2_AVAIL_ZONE=`curl -s http://169.254.169.254/latest/meta-data/placement/availability-zone` | |
EC2_REGION="`echo \"$EC2_AVAIL_ZONE\" | sed 's/[a-z]$//'`" | |
## Stop instance | |
/usr/local/bin/aws ec2 stop-instances --instance-ids "${INSTANCE_ID}" --region "${EC2_REGION}" 2>&1 | logger | |
fi | |
fi | |
rm -f ${LOCKFILE} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
sudo wget --quiet -O /usr/local/bin/self-stop https://gist.githubusercontent.com/adamar/15ec9db7b07bc529f98ff3f1b3492f6e/raw/528dfee5270bea8f894700b998fc8946de53aaf5/aws-self-stop && sudo chmod +x /usr/local/bin/self-stop && echo "/10 * * * * root /usr/local/bin/self-stop" | sudo tee /etc/cron.d/self-stop && echo '*/10 * * * * root /usr/local/bin/self-stop' | sudo tee /etc/cron.d/self-stop |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment