Skip to content

Instantly share code, notes, and snippets.

@tamsanh
Last active March 16, 2021 10:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tamsanh/92f0546322583dfd46f7d85d3510bdb7 to your computer and use it in GitHub Desktop.
Save tamsanh/92f0546322583dfd46f7d85d3510bdb7 to your computer and use it in GitHub Desktop.
Multi-Factor Authentication on AWS Cli
#########################################################################################################
# Call this script locally using:
# eval "$(curl --silent https://gist.githubusercontent.com/tamsanh/92f0546322583dfd46f7d85d3510bdb7/raw)"
# This will override current AWS environment variables
#########################################################################################################
# First type in a token code that will expire after at least 20 seconds
# Ex: TOKEN_CODE=192392
read -p TOKEN_CODE= TOKEN_CODE
# Get the serial number for your MFA device for your user.
# If multiple serial devices are available, will pick the first one that appears
SERIAL_NUMBER=`aws iam list-mfa-devices | grep SerialNumber | head -n 1 | cut -d \" -f 4`
# This next step will use the chosen serial number, and the given token code, and retrieve new credential data
NEW_CREDENTIALS=`aws sts get-session-token --serial-number $SERIAL_NUMBER --token-code $TOKEN_CODE`
# Finally, we parse the credential data, and export it to make it available to the console
export AWS_ACCESS_KEY_ID=`echo "$NEW_CREDENTIALS" | grep AccessKeyId | cut -d \" -f 4`
export AWS_SECRET_ACCESS_KEY=`echo "$NEW_CREDENTIALS" | grep SecretAccessKey | cut -d \" -f 4`
export AWS_SESSION_TOKEN=`echo "$NEW_CREDENTIALS" | grep SessionToken | cut -d \" -f 4`
# And echo the new credentials, in case one wants to use them in other places
echo "AWS_ACCESS_KEY_ID=$AWS_ACCESS_KEY_ID"
echo "AWS_SECRET_ACCESS_KEY=$AWS_SECRET_ACCESS_KEY"
echo "AWS_SESSION_TOKEN=$AWS_SESSION_TOKEN"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment