Skip to content

Instantly share code, notes, and snippets.

@kenzauros
Last active Oct 29, 2021
Embed
What would you like to do?
AWS CLI MFA
#!/bin/bash
CACHE_FILE=~/.aws/aws-mfa-cache
if [ -e $CACHE_FILE ]; then
source $CACHE_FILE
fi
if [ -z $AWS_ACCOUNT_ID ]; then
read -p "Account ID? " AWS_ACCOUNT_ID
else
read -p "Account ID? [$AWS_ACCOUNT_ID] " TMP_AWS_ACCOUNT_ID
AWS_ACCOUNT_ID=${TMP_AWS_ACCOUNT_ID:-$AWS_ACCOUNT_ID}
fi
if [ -z $AWS_USERNAME ]; then
read -p "Username? " AWS_USERNAME
else
read -p "Username? [$AWS_USERNAME] " TMP_AWS_USERNAME
AWS_USERNAME=${TMP_AWS_USERNAME:-$AWS_USERNAME}
fi
if [ -z $AWS_PROFILE ]; then
read -p "Profile? " AWS_PROFILE
else
read -p "Profile? [$AWS_PROFILE] " TMP_AWS_PROFILE
AWS_PROFILE=${TMP_AWS_PROFILE:-$AWS_PROFILE}
fi
if [ -z $AWS_PROFILE ]; then
echo "CANCELED"
exit 0
fi
AWS_CRED_FILE=~/.aws/credentials
if [ ! $(grep -E "\[$AWS_PROFILE\]" $AWS_CRED_FILE) ]; then
echo "Profile '$AWS_PROFILE' not found in $AWS_CRED_FILE. The following profiles are available."
grep -E "\[.+\]" $AWS_CRED_FILE | grep -ve "-mfa" | sed -r 's/^\[(.+)\]$/- \1/'
exit 1
fi
cat << EOT > $CACHE_FILE
AWS_ACCOUNT_ID=$AWS_ACCOUNT_ID
AWS_USERNAME=$AWS_USERNAME
AWS_PROFILE=$AWS_PROFILE
EOT
read -p "Code? " CODE
SESSION_JSON=$(aws --profile $AWS_PROFILE sts get-session-token --serial-number arn:aws:iam::$AWS_ACCOUNT_ID:mfa/$AWS_USERNAME --token-code $CODE --output json)
if [ $? -ne 0 ]; then
exit 1
fi
MFA_ACCESS_KEY=$(echo $SESSION_JSON | jq -r '.Credentials.AccessKeyId')
MFA_SECRET_ACCESS_KEY=$(echo $SESSION_JSON | jq -r '.Credentials.SecretAccessKey')
MFA_SESSION_TOKEN=$(echo $SESSION_JSON | jq -r '.Credentials.SessionToken')
MFA_EXPIRATION=$(echo $SESSION_JSON | jq -r '.Credentials.Expiration')
MFA_PROFILE_NAME=$AWS_PROFILE-mfa
aws --profile $MFA_PROFILE_NAME configure set aws_access_key_id $MFA_ACCESS_KEY
aws --profile $MFA_PROFILE_NAME configure set aws_secret_access_key $MFA_SECRET_ACCESS_KEY
aws --profile $MFA_PROFILE_NAME configure set aws_session_token $MFA_SESSION_TOKEN
echo "MFA profile: $MFA_PROFILE_NAME (expiration: $MFA_EXPIRATION)"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment