Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save mlehner616/7adedebce18e4c5388cf to your computer and use it in GitHub Desktop.
Save mlehner616/7adedebce18e4c5388cf to your computer and use it in GitHub Desktop.
#!/bin/bash -e
#
# Pass this script an AWS access key ID and it will show you what IAM user
# has that key.
#
# Usage:
# aws-access-key-to-iam-name some_key_id
#
readonly PROGNAME=$(basename $0)
readonly ARGS="$@"
check_command_exists() {
type "$1" &> /dev/null ;
if [ $? -eq 1 ]; then
echo >&2 "$1 is required, you must install it before using this script."
fi
}
get_all_iam_users() {
aws iam list-users --query "Users[].{UserName:UserName}" --output text > /tmp/aws_iam_users
}
get_all_access_key_ids() {
echo 'Iterating through all AWS IAM users.'
echo 'This may take a little while...'
echo ''
for user in `cat /tmp/aws_iam_users`
do
aws iam list-access-keys --user-name $user >> /tmp/aws_access_key_ids.json
done
}
find_and_show_access_key_owner() {
cat /tmp/aws_access_key_ids.json | grep -B 3 $ARGS | sed -e 's/^[ \t]*//'
}
cleanup() {
rm /tmp/aws_iam_users
rm /tmp/aws_access_key_ids.json
}
usage() {
cat <<- EOF
usage: $PROGNAME options
Finds the AWS IAM user that has a specific Access Key.
OPTIONS:
-h --help show this help
-x --debug debug mode
EXAMPLES:
Run:
$PROGNAME ABCDEFGHIJK123456789
Output:
"UserName": "my-iam-user",
"Status": "Active",
"CreateDate": "2014-06-26T13:44:04Z",
"AccessKeyId": "ABCDEFGHIJK123456789"
EOF
}
cmdline() {
local arg=
for arg
do
local delim=""
case "$arg" in
#translate --gnu-long-options to -g (short options)
--help) args="${args}-h ";;
--debug) args="${args}-x ";;
#pass through anything else
*) [[ "${arg:0:1}" == "-" ]] || delim="\""
args="${args}${delim}${arg}${delim} ";;
esac
done
#Reset the positional parameters to the short options
eval set -- $args
while getopts "hx:" OPTION
do
case $OPTION in
h)
usage
exit 0
;;
x)
readonly DEBUG='-x'
set -x
;;
esac
done
return 0
}
main() {
cmdline $ARGS
# Check pre-requisites
check_command_exists aws
get_all_iam_users
get_all_access_key_ids
# Main function call that will show the IAM user associated with the
# access key id passed as an arguement.
find_and_show_access_key_owner
# Get rid of cached lists when we're done.
cleanup
}
main
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment