Skip to content

Instantly share code, notes, and snippets.

@jakubigla
Last active October 14, 2021 07:15
Show Gist options
  • Save jakubigla/6a2c519910f8924d63b6c701a5650a85 to your computer and use it in GitHub Desktop.
Save jakubigla/6a2c519910f8924d63b6c701a5650a85 to your computer and use it in GitHub Desktop.
Start and Stop AWS EC2 instances based on tags
#!/bin/sh
set -e
function usage() {
echo "$0 [-r <region> -t <TAG_KEY=value ...>] (start|stop|status)"
}
while getopts "t:r:" o; do
case "${o}" in
t)
TAGS=${OPTARG}
;;
r)
REGION=${OPTARG}
;;
esac
done
shift $((OPTIND-1))
if [ $# -ne 1 ]; then
usage
exit 2
fi
if [ -z "$REGION" ]; then
REGION=$(aws configure get region)
fi
if [ ! -z "$TAGS" ]; then
TAGS=$(echo "$TAGS" | tr ',' ' ')
for PAIR in $TAGS; do
TAG_QUERY="Tags[?Key=='$(echo "$PAIR" | cut -d'=' -f1)' && Value=='$(echo "$PAIR" | cut -d'=' -f2)']"
if [ -z "$INSTANCES_QUERY" ]; then
INSTANCES_QUERY="?$TAG_QUERY"
else
INSTANCES_QUERY="$INSTANCES_QUERY && $TAG_QUERY"
fi
done
QUERY="Reservations[].Instances[$INSTANCES_QUERY].InstanceId"
fi
if [ -z "$QUERY" ]; then
QUERY="Reservations[].Instances[].InstanceId"
fi
INSTANCES=$(aws ec2 describe-instances --region "$REGION" --query "$QUERY" --output text)
EXIT=0
if [ "$1" = "start" ]; then
for instanceId in ${INSTANCES[@]}; do
echo "Starting instance $instanceId..."
aws ec2 start-instances --region "$REGION" --instance-ids "$instanceId"
done
EXIT=$?
elif [ "$1" = "stop" ]; then
for instanceId in ${INSTANCES[@]}; do
echo "Stopping instance $instanceId..."
aws ec2 stop-instances --region "$REGION" --instance-ids "$instanceId"
done
elif [ "$1" = "status" ]; then
for instanceId in ${INSTANCES[@]}; do
echo "$instanceId: $(aws ec2 describe-instance-status --region "$REGION" --instance-ids "$instanceId" --include-all-instances --query "InstanceStatuses[].[InstanceState][][Name]" --output text)"
done
EXIT=$?
else
usage
EXIT=2
fi
exit "$EXIT"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment