ssummer3
7/28/2015 - 2:38 PM

If your AWS key pair is restricted by MFA requirements, run this script as shown to contact STS and put temporary credentials into the envir

If your AWS key pair is restricted by MFA requirements, run this script as shown to contact STS and put temporary credentials into the environment that will last all day. Use these values in your CLI, Boto, or other script.

#!/bin/bash

# Adapted from original by Jaime Preciado-Beas (jpreciad@nd.edu)
# To export env variables to current shell
# run: . user-mfa.sh 

# check for user's mfa serial number
: ${AWS_MFA_SERIAL?"Need to set AWS_MFA_SERIAL. Locate at the bottom of your user page under AWS Console -> Identity and Access Management -> Users -> Your netID.  Field is labeled 'Multi-Factor Authentication Device'"}

unset AWS_ACCESS_KEY_ID
unset AWS_SECRET_ACCESS_KEY
unset AWS_SECURITY_TOKEN

echo -n 'Enter MFA token-code: '
read TOKEN

CRED=$(aws sts get-session-token --serial-number $AWS_MFA_SERIAL --duration-seconds 129600 --output text --token-code $TOKEN)

export AWS_ACCESS_KEY_ID=$(echo $CRED | cut -d ' ' -f 2)
export AWS_SECRET_ACCESS_KEY=$(echo $CRED | cut -d ' ' -f 4)
export AWS_SECURITY_TOKEN=$(echo $CRED | cut -d ' ' -f 5)

echo "All done!  This session will expire in 36 hours, or until you log into a fresh shell.  The following AWS ENV variables have been set:"
env | grep AWS