Skip to content

Instantly share code, notes, and snippets.

@Yloganathan
Created May 12, 2019 05:23
Show Gist options
  • Star 12 You must be signed in to star a gist
  • Fork 6 You must be signed in to fork a gist
  • Save Yloganathan/c24a3d99213c72c7316269a1888b2600 to your computer and use it in GitHub Desktop.
Save Yloganathan/c24a3d99213c72c7316269a1888b2600 to your computer and use it in GitHub Desktop.
Extended https://github.com/sweharris/aws-cli-mfa/blob/master/get-aws-creds and pushed the token, access key and Id to credentials
#!/bin/bash
# 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
exit 255
fi
identity=$(aws sts get-caller-identity)
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
exit 255
fi
echo You are: $username >&2
mfa=$(aws iam list-mfa-devices --user-name "$username")
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
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 --serial-number "$device" --token-code $code)
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
exit 255
fi
echo 'Removing old mfa setting'
sed -i '' '/mfa/,$d' ~/.aws/credentials
echo 'Push new mfa token, key, id to credentials'
echo AWS_SESSION_TOKEN=$session
echo AWS_SECRET_ACCESS_KEY=$secret
echo AWS_ACCESS_KEY_ID=$access
echo [mfa] >> ~/.aws/credentials
echo AWS_SESSION_TOKEN=$session >> ~/.aws/credentials
echo AWS_SECRET_ACCESS_KEY=$secret >> ~/.aws/credentials
echo AWS_ACCESS_KEY_ID=$access >> ~/.aws/credentials
echo Keys valid until $expire >&2
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment