Skip to content

Instantly share code, notes, and snippets.

@sofianhw
Last active January 18, 2022 16:29
Show Gist options
  • Save sofianhw/9197915c7e5232c92510c52d9ee72cf6 to your computer and use it in GitHub Desktop.
Save sofianhw/9197915c7e5232c92510c52d9ee72cf6 to your computer and use it in GitHub Desktop.
Script to stop, start, and check AWS EC2 state
#!/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