Last active
July 19, 2019 12:58
-
-
Save pataiji/c82aea02bcb4347e2474c94e7cab0af0 to your computer and use it in GitHub Desktop.
Get IPs of EC2 Instances across AWS profiles
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/bash | |
# Required | |
# - awscli | |
# - jq | |
PROGNAME=$(basename $0) | |
export IDENTIFYING_TAG_NAME='Name' | |
usage() { | |
echo "Usage: $PROGNAME [OPTIONS]" | |
echo | |
echo "Options:" | |
echo " -p, --profile ARG" | |
echo " -t, --tag-name ARG" | |
echo " -a, --all" | |
echo " --csv" | |
echo | |
exit 1 | |
} | |
_ec2_ips() { | |
aws ec2 describe-instances \ | |
| jq '{ Results: [ | |
.Reservations[].Instances[] | |
| { | |
Profile: env.AWS_PROFILE, | |
InstanceId: .InstanceId, | |
State: .State.Name, | |
(env.IDENTIFYING_TAG_NAME): (.Tags | arrays | map(if .Key == env.IDENTIFYING_TAG_NAME then .Value else null end) | join("")), | |
PrivateIp: ( [ .NetworkInterfaces[].PrivateIpAddresses[] | .PrivateIpAddress ] | join(",") ), | |
PublicIp: ( [ .NetworkInterfaces[].PrivateIpAddresses[] | .Association.PublicIp ] | unique | join(",") ) | |
} | |
] }' | |
} | |
_ec2_ips_across_profiles() { | |
PROFILES=$(cat ~/.aws/config | grep profile | sed -E 's/\[profile ([a-z0-9_-]+)\]/\1/') | |
_tmp='' | |
for profile in $PROFILES; | |
do | |
export AWS_PROFILE=$profile | |
_tmp=$_tmp$(_ec2_ips) | |
done | |
echo $_tmp | jq -s '{ Results: ([ .[].Results ] | flatten) }' | |
} | |
# ref. https://qiita.com/b4b4r07/items/dcd6be0bb9c9185475bb | |
for OPT in "$@" | |
do | |
case "$OPT" in | |
'-h'|'--help' ) | |
usage | |
exit 1 | |
;; | |
'-a'|'--all' ) | |
MODE='ALL' | |
shift | |
;; | |
'--csv' ) | |
FORMAT='CSV' | |
shift | |
;; | |
'-t'|'--tag-name' ) | |
if [[ -z "$2" ]] || [[ "$2" =~ ^-+ ]]; then | |
echo "$PROGNAME: option requires an argument -- $1" 1>&2 | |
exit 1 | |
fi | |
export IDENTIFYING_TAG_NAME="$2" | |
shift 2 | |
;; | |
'-p'|'--profile' ) | |
if [[ -z "$2" ]] || [[ "$2" =~ ^-+ ]]; then | |
echo "$PROGNAME: option requires an argument -- $1" 1>&2 | |
exit 1 | |
fi | |
export AWS_PROFILE="$2" | |
shift 2 | |
;; | |
-*) | |
echo "$PROGNAME: illegal option -- '$(echo $1 | sed 's/^-*//')'" 1>&2 | |
exit 1 | |
;; | |
esac | |
done | |
case "$MODE" in | |
'ALL' ) | |
_results=$(_ec2_ips_across_profiles) | |
;; | |
*) | |
_results=$(_ec2_ips) | |
;; | |
esac | |
case "$FORMAT" in | |
'CSV' ) | |
echo "\"Profile\",\"InstanceId\",\"State\",\"$IDENTIFYING_TAG_NAME\",\"PrivateIp\",\"PublicIp\"" | |
echo $_results | jq -r '.Results[] | flatten | @csv' | |
;; | |
*) | |
echo $_results | jq | |
;; | |
esac |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment