Skip to content

Instantly share code, notes, and snippets.

@rodgtr1
Created July 2, 2021 14:13
Show Gist options
  • Save rodgtr1/6ae49449b836ff617ed0b0863ca3110f to your computer and use it in GitHub Desktop.
Save rodgtr1/6ae49449b836ff617ed0b0863ca3110f to your computer and use it in GitHub Desktop.
Script to authenticate with AWS CLI with MFA token
#!/bin/bash
set -e
# specify your MFA_DEVICE_ARN
MFA_DEVICE_ARN=YOURMFAARN
PATH_TO_CREDENTIALS_FILE=/path/to/.aws/credentials
echo $PATH_TO_CREDENTIALS_FILE
#1H = 3600
#2H = 7200
#3H = 10800
#4H = 14400
#5H = 18000
#6H = 21600
#7H = 25200
TOKEN_DURATION_IN_SECONDS=21600
if [ MFA_DEVICE_ARN = YOUR_MFA_ARN ]; then
echo "Please specify the MFA_DEVICE_ARN"
exit 1
fi
if [ -z $TOKEN_DURATION_IN_SECONDS ]; then
echo "Please specify the TOKEN_DURATION_IN_SECONDS"
exit 1
fi
read -p "Please enter MFA code: " MFA_CODE
echo "You entered '$MFA_CODE'"
COMMAND="aws --output text sts get-session-token \
--serial-number $MFA_DEVICE_ARN \
--token-code $MFA_CODE \
--duration $TOKEN_DURATION_IN_SECONDS"
echo $COMMAND
CREDS=$($COMMAND)
KEY=$(echo $CREDS | cut -d" " -f2)
SECRET=$(echo $CREDS | cut -d" " -f4)
SESS_TOKEN=$(echo $CREDS | cut -d" " -f5)
if grep -w "mfa" .aws/credentials
then
sed -i '/mfa/,$d' .aws/credentials
fi
echo "[mfa]" >> $PATH_TO_CREDENTIALS_FILE
echo "aws_access_key_id = $KEY" >> $PATH_TO_CREDENTIALS_FILE
echo "aws_secret_access_key = $SECRET" >> $PATH_TO_CREDENTIALS_FILE
echo "aws_session_token = $SESS_TOKEN" >> $PATH_TO_CREDENTIALS_FILE
@rodgtr1
Copy link
Author

rodgtr1 commented Aug 28, 2021

If on a mac, like 45 needs to be changed to:
sed -i '' -e '/mfa/,$d' .aws/credentials

@hamaadshah
Copy link

hamaadshah commented Oct 20, 2022

Shouldn't that be $PATH_TO_CREDENTIALS_FILE? Instead of .aws/credentials? One might have the shell in a directory other than the home directory.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment