Skip to content

Instantly share code, notes, and snippets.

@stask
Last active December 11, 2015 05:58
Show Gist options
  • Save stask/4555635 to your computer and use it in GitHub Desktop.
Save stask/4555635 to your computer and use it in GitHub Desktop.
Wrapper to search EC2 machines by name tag. Shows only running instances.
#!/usr/bin/env bash
if [ -z "$EC2_PRIVATE_KEY" ]; then
echo "EC2_PRIVATE_KEY is not defined"
exit 1
fi
if [ -z "$EC2_CERT" ]; then
echo "EC2_CERT is not defined"
exit 1
fi
OUTPUT=`ec2din --show-empty-fields --headers --filter="instance-state-name=running" --filter="tag:Name=$1"`
IFS=$'\n'$'\r'
INSTANCE_LINES=( $(echo "$OUTPUT"|grep "^INST"|cut -f 2,4,5,10,12) )
NAME_LINES=( $(echo "$OUTPUT"|grep "^TAG"|grep "Name"|cut -f 3,5) )
IFS=$'\t'
{
echo -e "name\tinstance-id\tpublic-dns\tprivate-dns\ttype\tAZ"
for (( i=0; i<${#INSTANCE_LINES[*]}; i++ ))
do
# 0 - instance id
# 1 - public dns
# 2 - internal dns
# 3 - type
# 4 - AZ
INSTANCE_DETAILS=( ${INSTANCE_LINES[i]} )
# 0 - instance id
# 1 - name tag
NAME_DETAILS=( ${NAME_LINES[i]} )
# validate that it's the same instance?
echo -e "${NAME_DETAILS[1]}\t${INSTANCE_DETAILS[0]}\t${INSTANCE_DETAILS[1]}\t${INSTANCE_DETAILS[2]}\t${INSTANCE_DETAILS[3]}\t${INSTANCE_DETAILS[4]}"
done;
} | column -t
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment