Skip to content

Instantly share code, notes, and snippets.

@grosendorf
Created May 19, 2017 13:01
Show Gist options
  • Save grosendorf/ff2d727920de69860cd712f9e6bef49d to your computer and use it in GitHub Desktop.
Save grosendorf/ff2d727920de69860cd712f9e6bef49d to your computer and use it in GitHub Desktop.
Get MFA verified, temporary AWS access/secret keys.
#!/bin/bash
set -eo pipefail
usage () {
cat << HEREDOC
Usage:
eval "\$(./authenticate MFA_TOKEN)"
Gets temporary AWS credentials which have been verified using MFA. Requires
the user to configure the aws cli to use their long lived credentials for
the account, and for that profile to be active in the current shell. The
temporary credentials are set as standard AWS environment variables:
- AWS_ACCESS_KEY_ID
- AWS_SECRET_ACCESS_KEY
- AWS_SESSION_TOKEN
HEREDOC
}
AWSCLI=$(which aws)
MFA_TOKEN=$1
if [ -z $MFA_TOKEN ]; then
usage
exit 1
fi
unset AWS_ACCESS_KEY_ID
unset AWS_SECRET_ACCESS_KEY
unset AWS_SESSION_TOKEN
USERNAME=$(${AWSCLI} iam get-user --query 'User.UserName' --output text)
QUERY="VirtualMFADevices[?User.UserName=='${USERNAME}'].[SerialNumber]"
MFA_SERIAL=$(${AWSCLI} iam list-virtual-mfa-devices --query "${QUERY}" --output text)
CREDS=$(${AWSCLI} sts get-session-token \
--token-code ${MFA_TOKEN} \
--serial-number ${MFA_SERIAL} \
--output text \
--query "Credentials.[AccessKeyId, SecretAccessKey, SessionToken]")
echo "export AWS_ACCESS_KEY_ID=$(echo $CREDS | awk '{print $1}')"
echo "export AWS_SECRET_ACCESS_KEY=$(echo $CREDS | awk '{print $2}')"
echo "export AWS_SESSION_TOKEN=$(echo $CREDS | awk '{print $3}')"
echo "export AWS_SECURITY_TOKEN=$(echo $CREDS | awk '{print $3}')"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment