Created
February 4, 2020 17:27
-
-
Save yardbirdsax/7926e18a21de072e28273155bdcbb163 to your computer and use it in GitHub Desktop.
AWS Get Auth Token with MFA
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
# This script calls the AWS STS API and retrieves a temporary session token. | |
usage() | |
{ | |
cat <<EOM | |
Usage: \$(aws-get-auth-token <auth token here>) | |
It's important to call as shown above with the dollar sign, so that the command generated by the script gets executed. | |
EOM | |
exit 0 | |
} | |
error_exit() | |
{ | |
echo "$1" 1>&2 | |
exit 1 | |
} | |
[[ $# -eq 0 ]] && usage; | |
# Clear all env variables | |
export AWS_ACCESS_KEY_ID= | |
export AWS_SECRET_ACCESS_KEY= | |
export AWS_SESSION_TOKEN= | |
# Get the current user name and account | |
RESULTS=`aws sts get-caller-identity` | |
USERNAME=`echo $RESULTS | jq '.Arn' -r | sed 's/.*\/\(.*\)/\1/'` | |
ACCOUNT=`echo $RESULTS | jq '.Account' -r` | |
echo "User name is '$USERNAME'. Account ID is $ACCOUNT." | |
# Get an auth token response | |
MFA_SERIAL_NUM="arn:aws:iam::$ACCOUNT:mfa/$USERNAME" | |
echo "MFA Serial number is $MFA_SERIAL_NUM" | |
RESULTS=`aws sts get-session-token --serial-number $MFA_SERIAL_NUM --token $1` | |
if [ "$?" != "0" ]; then | |
error_exit "Could not acquire session token from AWS. Review output." | |
fi | |
# Export the environment variables | |
echo export AWS_ACCESS_KEY_ID=`echo $RESULTS | jq '.Credentials.AccessKeyId' -r` | |
echo export AWS_SECRET_ACCESS_KEY=`echo $RESULTS | jq '.Credentials.SecretAccessKey' -r` | |
echo export AWS_SESSION_TOKEN=`echo $RESULTS | jq '.Credentials.SessionToken' -r` |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment