Skip to content

Instantly share code, notes, and snippets.

@holly
Last active March 25, 2023 14:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save holly/7356b59ed9433caaae793db04d8a59bd to your computer and use it in GitHub Desktop.
Save holly/7356b59ed9433caaae793db04d8a59bd to your computer and use it in GitHub Desktop.
easy ec2 start|stop script
#!/bin/bash
MODE=$1
#get_instances() {
#aws ec2 describe-instances --filter "Name=instance-state-name,Values=${STATE}" "Name=tag:Environment,Values=development" | jq -r '.Reservations[].Instances[] | [ .InstanceId, (.Tags[] | select(.Key == "Name").Value) ] | @csv'
#aws ec2 describe-instances --filter "Name=instance-state-name,Values=${state}" "Name=tag:Environment,Values=development" | jq -r '.Reservations[].Instances[] | .InstanceId'
#}
describe_instances() {
aws ec2 describe-instances | jq -r '.Reservations[].Instances[] | [ .InstanceId, (.Tags[] | select(.Key == "Name").Value), .State.Name ] | @tsv'
}
_instances_ctrl() {
if [ $MODE = "start" ]; then
instance_ids=$(describe_instances | perl -lae 'print $F[0] if $F[2] eq "stopped"')
check_state="running"
fi
if [ $MODE = "stop" ]; then
instance_ids=$(describe_instances | perl -lae 'print $F[0] if $F[2] eq "running"')
check_state="stopped"
fi
if [ -z "${instance_ids}" ]; then
echo "target instances are not exists."
return
fi
echo "$instance_ids" | xargs --no-run-if-empty aws ec2 ${MODE}-instances --instance-ids
echo "$instance_ids" | while read instance_id; do
while true; do
current_state=$(aws ec2 describe-instances --instance-ids $instance_id | jq -r '.Reservations[].Instances[] | .State.Name')
if [ $current_state = $check_state ]; then
echo "$instance_id is $check_state."
break
fi
sleep 1
done
done
}
case "$MODE" in
"describe" )
describe_instances ;;
"start" | "stop" )
_instances_ctrl ;;
* )
echo "usage: $0 [describe|stop|start]"; exit 1;;
esac
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment