Skip to content

Instantly share code, notes, and snippets.

@jakerella
Created November 24, 2021 20:33
Show Gist options
  • Save jakerella/ab9028382a4f5b333a8d9a47f8b281a1 to your computer and use it in GitHub Desktop.
Save jakerella/ab9028382a4f5b333a8d9a47f8b281a1 to your computer and use it in GitHub Desktop.
A script for logging into the AWS CLI using MFA
% login-aws () {
valid_token=0
duration=129600
if [ "$1" = '--help' ] || [ "$1" = '-h' ] || [ "$1" = 'help' ]; then
echo "This script will log you into AWS using an MFA device."
echo "If you have logged in recently (36 hours), then this script will use"
echo "the existing session information. Session information is stored in"
echo "the user's home directory as a JSON file named '.aws_session_token'"
echo "\nBe sure to have the AWS_MFA environment variable set to the arn of"
echo "your virtual MFA device from the AWS console! This should look like:"
echo " arn:aws:iam::123456789012:mfa/username"
echo "\nUsage: login-aws MFA-code [--new]"
echo " MFA_CODE The OTP code from your virtual MFA device"
echo " --new Force a re-auth with AWS (removing the old session token)"
return
fi
if (( $# == 2 )) && [ "$2" = '--new' ]; then
echo "Removing old session token..."
rm -f ~/.aws_session_token
fi
if [[ -a ~/.aws_session_token ]]; then
token=$(cat ~/.aws_session_token)
valid_token=1
expiration_date=$(jq -r '.Credentials.Expiration' <<< $token)
expiration_ts=$(date -u -j -f "%Y-%m-%dT%H:%M:%S" "$expiration_date" "+%s")
now=$(date -u +%s)
if (( expiration_ts < now )); then
echo "Session expired, removing old session info..."
rm -f ~/.aws_session_token
valid_token=0
fi
fi
if (( $valid_token == 0 )); then
echo "No existing session, authenticating with AWS..."
if [[ ! -v AWS_MFA ]]; then
echo "Please set the AWS_MFA environment variable to the arn of your MFA device."
return
fi
if (( $# == 0 )); then
echo "Please enter the MFA OTP code from your virtual device:\nlogin-aws MFA-CODE"
return
fi
unset AWS_ACCESS_KEY_ID
unset AWS_SECRET_ACCESS_KEY
unset AWS_SESSION_TOKEN
token=$(aws sts get-session-token --serial-number $AWS_MFA --duration-seconds $duration --token-code $1)
if [ "$token" = '' ]; then
echo "Unable to save session token."
return
fi
fi
echo "$token" > ~/.aws_session_token
accesskeyid=$(jq -r '.Credentials.AccessKeyId' <<< $token)
secretaccesskey=$(jq -r '.Credentials.SecretAccessKey' <<< $token)
sessiontoken=$(jq -r '.Credentials.SessionToken' <<< $token)
export AWS_ACCESS_KEY_ID="$accesskeyid"
export AWS_SECRET_ACCESS_KEY="$secretaccesskey"
export AWS_SESSION_TOKEN="$sessiontoken"
echo "Session token retrieved and set in environment variables."
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment