#!/bin/bash
# Runs the same aws CLI command in "most" of the defined profiles
# in $HOME/.aws/config
#
# You can pass in via an environment variable a "profile set"
# of either "commercial", "govcloud", or "both".  Default is "both"
#
# Does an "aws sts get-caller-identity" to confirm that your AssumeRole
# and other necessities are properly set up before attempting to call the
# actual AWS command.
#
# PROFILE_SET=commercial aws-all.sh ec2 describe-instances
#
set -eu -o pipefail

AWS=${AWS:-/usr/local/bin/aws}
PROFILE_SET=${PROFILE_SET:-both}

ALL_PROFILES=$( egrep "\[profile" ~/.aws/config | 	\
		awk '{ print $2 }' | 			\
		sed "s/\]//" | 				\
		egrep -v "default|commercial|govcloud" )

COMMERCIAL_PROFILES=""
GOVCLOUD_PROFILES=""

for i in $ALL_PROFILES; do
	if [[ "$i" =~ -gov$ ]]; then
		GOVCLOUD_PROFILES="$GOVCLOUD_PROFILES $i"
	else
		COMMERCIAL_PROFILES="$COMMERCIAL_PROFILES $i"
	fi
done

case $PROFILE_SET in

	both) 
		PROFILES="$COMMERCIAL_PROFILES $GOVCLOUD_PROFILES"
		;;
	
	govcloud) 
		PROFILES="$GOVCLOUD_PROFILES"
		;;

	commercial) 
		PROFILES="$COMMERCIAL_PROFILES"
		;;
esac

for i in $PROFILES; do

	echo "======================================================================================"
	export AWS_PROFILE=$i 
	
	set +e
	${AWS} sts get-caller-identity > /dev/null 2>&1
	RC=$?
	set -e

	if [[ $RC -eq 0 ]]; then
		echo "GetCallerIdentity (AssumeRole Test) for $i OK"
		aws $*
	else
		echo "GetCallerIdentity (AssumeRole Test) for $i FAILED"
	fi
 done
