Skip to content

Instantly share code, notes, and snippets.

@kirikaza
Last active December 19, 2015 21:59
Show Gist options
  • Save kirikaza/6024236 to your computer and use it in GitHub Desktop.
Save kirikaza/6024236 to your computer and use it in GitHub Desktop.
Finds AWS EC2 instances by name mask.
#!/bin/bash
if ! aws --version 2> /dev/null ; then
echo >&2 "command \`aws' is not found; maybe awscli is not installed"
exit 1
fi
if ! jq --version 2> /dev/null ; then
echo >&2 "command \`jq' is not found; maybe jq is not installed"
exit 1
fi
usage() {
cat >&2 <<__
Usage: aws-ec2-find.sh [PROFILE] NAME_MASK
Where
- PROFILE is a profile name from ~/.aws (used by awscli).
If it isn't specified, default section from ~/.aws is applied.
- NAME_MASK is a wildcard for name of ec2 instance(s).
__
}
case $# in
1)
profile=
name_mask="$1"
;;
2)
profile="$1"
name_mask="$2"
;;
*)
usage
exit 2
;;
esac
if [ -z "$name_mask" ] ; then
usage
exit 2
fi
aws_filter="name=tag:Name,values=$name_mask"
jq_filter='
.Reservations[].Instances[] |
.PublicDnsName // "-",
(
(.Tags // []) |
map(select(.Key=="Name"))
[].Value // "-"
)
'
dns_longest='ec2-123-123-123-123.compute-1.amazonaws.com'
output=`
aws ${profile:+--profile "$profile"} \
ec2 describe-instances --filters "$aws_filter"
`
result=$?
if [ $result -ne 0 ] ; then
echo >&2 "$output"
exit $result
fi
echo "$output" |
jq "$jq_filter" |
xargs -n2 printf "%${#dns_longest}s %s\\n"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment