Skip to content

Instantly share code, notes, and snippets.

@brandonrich
Last active April 15, 2016 21:02
Show Gist options
  • Save brandonrich/1847f551d28bae52b4f6 to your computer and use it in GitHub Desktop.
Save brandonrich/1847f551d28bae52b4f6 to your computer and use it in GitHub Desktop.
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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment