AWS MFA Bash Script

Mark Bixler
2 min readMay 1, 2018

--

Much of the work I do is running AWS Python lambda functions locally on my Mac, so I don’t have to login to the AWS console to run them.

The standard way of dealing with your MFA tokens is to run the ‘aws sts’ command with your MFA arn serial-number, then take the values generated from that command, and paste them into your .aws/credentials file. This is a bit tedious and also prone to error as you’re copying 3 different values and it’s also easy to miss a character or two when copying.

A solution to this that I’ve found, is creating a shell script that prompts me for my MFA token, and then automatically take the values and updates my .aws/credentials file for me. These tokens are then valid for 12 hours of use.

Now, each morning when I get to work, I simply open a terminal session and run “./mfa.sh” enter my MFA token and ‘Wa-la!’, I’m all set.

The following screenshot is my code (with my private information blocked out).

mfa.sh
#!/bin/sh# Create Filename Variable
FILE_NAME=.aws/credentials
# Clear File of Previous Contents
> $FILE_NAME
# Save Default Key Information for MFA Command
echo "[default]" >> $FILE_NAME
echo "aws_access_key_id = " >> $FILE_NAME
echo "aws_secret_access_key = " >> $FILE_NAME
# Prompt for MFA
echo "Enter MFA Code:"
read varname
# Run AWS Token Command
value=$(aws sts get-session-token --serial-number arn:aws:iam:: --token-code $varname)
# Clear File Again & Store New Keys
> $FILE_NAME
access_key_id=$(echo $value | awk '{print $11}' | tr -d '"' | tr -d ',')
secret_access_key=$(echo $value | awk '{print $5}' | tr -d '"' | tr -d ',')
session_token=$(echo $value | awk '{print $7}' | tr -d '"' | tr -d ',')
echo >> $FILE_NAME
echo "[default]" >> $FILE_NAME
echo "aws_access_key_id = $access_key_id" >> $FILE_NAME
echo "aws_secret_access_key = $secret_access_key" >> $FILE_NAME
echo "aws_session_token = $session_token" >> $FILE_NAME

This method is for a single AWS account. For multiple account management there are various ways to handle that using the code above as a foundation, and just add in further intelligence around it to handle the different account numbers and user logins.

Feel free to use this same code in your environment and as always, let me know of any issues, improvements of comments to enhance the script.

--

--

Mark Bixler
Mark Bixler

Written by Mark Bixler

Platform Architect @mindbody. Passion for automating my work and for trolling my friends

Responses (5)