Skip to content

Instantly share code, notes, and snippets.

@ashiklom
Last active May 21, 2024 14:37
Show Gist options
  • Save ashiklom/79e5948cb5de3796066e59a95cd1e4b1 to your computer and use it in GitHub Desktop.
Save ashiklom/79e5948cb5de3796066e59a95cd1e4b1 to your computer and use it in GitHub Desktop.
AWS MFA script
#!/bin/bash
if (return 0 2> /dev/null)
then
: # Pass
else
echo 'This script must be `source`d, not executed!'
exit 255
fi
# This uses MFA devices to get temporary (eg 12 hour) credentials. Requires
# a TTY for user input.
#
# GPL 2 or higher
if [ ! -t 0 ]
then
echo Must be on a tty >&2
echo "Exiting..."
# exit 255
fi
AWSPROFILE=${1:-auth}
echo "Using AWS profile: $AWSPROFILE"
identity=$(aws sts get-caller-identity --profile "$AWSPROFILE" --output json)
username=$(echo -- "$identity" | sed -n 's!.*"arn:aws:iam::.*:user/\(.*\)".*!\1!p')
if [ -z "$username" ]
then
echo "Can not identify who you are. Looking for a line like
arn:aws:iam::.....:user/FOO_BAR
but did not find one in the output of
aws sts get-caller-identity
$identity" >&2
echo "Exiting..."
# exit 255
fi
echo You are: $username >&2
mfa=$(aws iam list-mfa-devices --profile "$AWSPROFILE" --user-name "$username" --output json)
device=$(echo -- "$mfa" | sed -n 's!.*"SerialNumber": "\(.*\)".*!\1!p')
if [ -z "$device" ]
then
echo "Can not find any MFA device for you. Looking for a SerialNumber
but did not find one in the output of
aws iam list-mfa-devices --username \"$username\"
$mfa" >&2
echo "Exiting..."
# exit 255
fi
echo Your MFA device is: $device >&2
echo -n "Enter your MFA code now: " >&2
read code
tokens=$(aws sts get-session-token --profile "$AWSPROFILE" --serial-number "$device" --token-code $code --output json)
secret=$(echo -- "$tokens" | sed -n 's!.*"SecretAccessKey": "\(.*\)".*!\1!p')
session=$(echo -- "$tokens" | sed -n 's!.*"SessionToken": "\(.*\)".*!\1!p')
access=$(echo -- "$tokens" | sed -n 's!.*"AccessKeyId": "\(.*\)".*!\1!p')
expire=$(echo -- "$tokens" | sed -n 's!.*"Expiration": "\(.*\)".*!\1!p')
if [ -z "$secret" -o -z "$session" -o -z "$access" ]
then
echo "Unable to get temporary credentials. Could not find secret/access/session entries
$tokens" >&2
echo "Exiting..."
# exit 255
fi
export AWS_ACCESS_KEY_ID=$access
export AWS_SECRET_ACCESS_KEY=$secret
export AWS_SESSION_TOKEN=$session
echo "
Credentials expire: $expire
AWS_ACCESS_KEY_ID=$access
AWS_SECRET_ACCESS_KEY=$secret
AWS_SESSION_TOKEN=$session
"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment