Skip to content

Instantly share code, notes, and snippets.

@louiszuckerman
Last active August 15, 2017 22:43
Show Gist options
  • Save louiszuckerman/4489065 to your computer and use it in GitHub Desktop.
Save louiszuckerman/4489065 to your computer and use it in GitHub Desktop.
easy ssh access and pruning for EC2 instances in AutoScaling groups. depends on AWS CLI.
#!/bin/bash
if [ "$1" == "-h" ]; then
cat <<END
AWS AutoScaling Termination Helper:
terminate an instance in an auto scaling group
Usage: $0 {group-name}
END
exit
fi
INSTANCES=$(aws autoscaling describe-auto-scaling-groups --auto-scaling-group-names $1 --query 'AutoScalingGroups[0].Instances[]' --output text)
INSTANCEIDS=$(awk '{print $3}' <<<"$INSTANCES")
COUNT=$(wc -l <<<"$INSTANCES")
IFS=$'\n'
c=1
for i in $INSTANCES; do
echo $((c++)): $i
done
read -p "Which one? " N
if [[ "$N" == "" || "$N" != [0-9]* || "$N" -gt "$COUNT" ]]; then
echo ERROR: Invalid selection
exit
fi
read -p "Replace? [Y/n] " R
if [[ "$R" != [nN] ]]; then
TERMREPL=REPLACE
DECREMENT='--no-should-decrement-desired-capacity'
else
TERMREPL=TERMINATE
DECREMENT='--should-decrement-desired-capacity'
fi
SELECTEDID=$(head "-$N" <<<"$INSTANCEIDS" | tail -1)
SELECTEDLINE=$(head "-$N" <<<"$INSTANCES" | tail -1)
echo About to $TERMREPL instance $N: $SELECTEDLINE
read -p "Are you sure? [y/N] " S
if [[ "$S" != [yY] ]]; then
echo Aborting.
exit
else
echo Proceeding.
aws autoscaling terminate-instance-in-auto-scaling-group $DECREMENT --instance-id $SELECTEDID
fi
#!/bin/bash
if [ "$1" == "-h" ]; then
cat <<END
AWS AutoScaling SSH Helper:
connects to an autoscaling instance by ssh
Usage: $0 {group-name} [index]
END
exit
fi
INSTANCES=$(aws autoscaling describe-auto-scaling-groups --auto-scaling-group-names $1 --query 'AutoScalingGroups[0].Instances[]' --output text)
INSTANCEIDS=$(awk '{print $3}' <<<"$INSTANCES")
COUNT=$(wc -l <<<"$INSTANCES")
if [ $COUNT == 1 ]; then
N="1"
elif [ "$2" != "" ]; then
N=$2
else
IFS=$'\n'
c=1
for i in $INSTANCES; do
echo $((c++)): $i
done
read -p "Which one? [1] " N
if [[ "$N" == "" || "$N" != [0-9]* || "$N" -gt "$COUNT" ]]; then
N="1"
fi
fi
SELECTEDID=$(head "-$N" <<<"$INSTANCEIDS" | tail -1)
SELECTEDLINE=$(head "-$N" <<<"$INSTANCES" | tail -1)
echo Selected $N: $SELECTEDLINE
ssh $(aws ec2 describe-instances --instance-ids $SELECTEDID --query "Reservations[0].Instances[0].PublicIpAddress" --output text)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment