Skip to content

Instantly share code, notes, and snippets.

@burdandrei
Created May 18, 2020 09:43
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save burdandrei/ba3b595c69e1f6f91e4b1495a65b93c9 to your computer and use it in GitHub Desktop.
Save burdandrei/ba3b595c69e1f6f91e4b1495a65b93c9 to your computer and use it in GitHub Desktop.
Wrapper for CSSH running instances by tag
#!/usr/bin/env bash
#
# Wrapper for CSSH running instances by tag
usage(){
cat << EOF >&2
usage: $0 options
This script Gathers instances from AWS and runs ClusterSSH to them
OPTIONS:
-p AWS Profile
-t AWS Tags to Search the machines Name=Value space separated
-s Single mode: ssh only to one machine
-e Use PublicDnsName to connect. Default: PrivateIpAddress
-i Use PrivateDnsName to connect. Default: PrivateIpAddress
EOF
}
EP=PrivateIpAddress
while getopts "p: t: o: s e l i" OPTION; do
case $OPTION in
p)
PROFILE=$OPTARG
;;
t)
TAGS=$OPTARG
;;
o)
OPTIONS=$OPTARG
;;
s)
mode='single'
;;
e)
EP='PublicDnsName'
;;
i)
EP='PrivateDnsName'
;;
l)
LIST_ONLY=true
;;
?)
usage
exit
;;
esac
done
if [[ -z $PROFILE ]]; then
PROFILE="default"
fi
if [[ -z $TAGS ]]; then
echo "No Tags provided" >&2
usage
exit 1
fi
FILTERS=""
LENGTH=$(echo "$TAGS" | awk '{print NF}')
for i in $(eval echo "{1..$LENGTH}"); do
FILTERS+=$(echo -n "$TAGS" | awk "{print \$$i}" | awk -F "=" '{print " \"Name=tag:"$1",Values="$2"\""}')
done
BASE_QUERY="aws ec2 describe-instances \
--profile $PROFILE \
--query Reservations[].Instances[].${EP} \
--output text \
--filters \"Name=instance-state-name,Values=running\""
BASE_QUERY+=$FILTERS
AWS_ANSWER=$(eval $BASE_QUERY)
HOST_COUNT=$(echo $AWS_ANSWER | awk '{print NF}')
if [[ $HOST_COUNT -lt 1 ]]; then
echo "No machines found, check the query" >&2
exit
fi
if [[ $LIST_ONLY == true ]]; then
echo $AWS_ANSWER
exit 0
fi
if [[ "$mode" == "single" ]]; then
FIRST_MACHINE=$(echo $AWS_ANSWER | awk '{print $1}')
ssh $OPTIONS $FIRST_MACHINE
else
cssh -o "$OPTIONS" $AWS_ANSWER
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment