Created
January 22, 2018 13:31
-
-
Save Pierozi/455f11fbb624500ce08d056dc12ba4af to your computer and use it in GitHub Desktop.
Automatic Stop AWS EC2 Bastion Instance each hour if no SSH connection established
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 | |
| # Copyright (c) 2018, Pierre Tomasina | |
| INSTANCE_ID=`curl -s http://169.254.169.254/latest/meta-data/instance-id` | |
| EC2_REGION=`curl -s http://169.254.169.254/latest/meta-data/placement/availability-zone | rev | cut -c 2- | rev` | |
| SSH_RUNNING=`netstat -nap | grep ESTABLISHED | grep sshd` | |
| uptimeMore60min=`cat /proc/uptime | awk '{print $1/60" > 60"}' | bc -l` | |
| if [ 0 -eq $uptimeMore60min ];then | |
| echo "Less then hour, do not stop instance" | |
| exit 0 | |
| fi | |
| if [ -z "$SSH_RUNNING" ];then | |
| echo "stopping the instance $INSTANCE_ID in $EC2_REGION" | |
| aws ec2 stop-instances --instance-ids $INSTANCE_ID --region $EC2_REGION | |
| fi |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment