Last active
January 18, 2022 16:29
-
-
Save sofianhw/9197915c7e5232c92510c52d9ee72cf6 to your computer and use it in GitHub Desktop.
Script to stop, start, and check AWS EC2 state
This file contains 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 | |
instancename=$1 | |
cmd=$2 | |
# get instances id | |
instanceid=$(aws \ | |
ec2 \ | |
describe-instances \ | |
--filters 'Name=tag:Name,Values=*'${instancename}'*' \ | |
--query 'Reservations[*].Instances[*].InstanceId' \ | |
--output text | tr '\n' ' ') | |
# on or off instances | |
case $2 in | |
on) | |
echo "On $instanceid" | |
aws ec2 start-instances --instance-ids $instanceid \ | |
--query 'StartingInstances[*].[InstanceId, CurrentState.Name]' --output text | |
;; | |
off) | |
echo "Off $instanceid" | |
aws ec2 stop-instances --instance-ids $instanceid \ | |
--query 'StartingInstances[*].[InstanceId, CurrentState.Name]' --output text | |
;; | |
check) | |
echo "Check $instanceid" | |
aws ec2 describe-instances --filters 'Name=tag:Name,Values='${instancename}' *' \ | |
--query 'Reservations[*].Instances[*].[InstanceId, State.Name]' --output text | |
;; | |
*) | |
echo "aws-on-off [instance name] [on/off/check]" | |
;; | |
esac |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment