Skip to content

Instantly share code, notes, and snippets.

@anniejw6
Forked from mick/alias.sh
Last active January 3, 2020 21:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save anniejw6/6988c31b85b75f878256712ff61208e1 to your computer and use it in GitHub Desktop.
Save anniejw6/6988c31b85b75f878256712ff61208e1 to your computer and use it in GitHub Desktop.
mfa for aws cli
  • Install AWS CLI version 1: https://docs.aws.amazon.com/cli/latest/userguide/install-cliv1.html
  • Run aws configure once installed
  • Put alias.sh, mfa.cfg, and mfa.sh in ~/.aws/
  • Modify mfa.cfg with the MFA device ID located on the same page as (and directly below) where you found your AWS access and secret key
  • Add source ~/.aws/alias.sh in .bashrc or .zshrc
  • Source your .bashrc or .zshrc
  • Run awsmfa followed by your MFA code, e.g., awsmfa 111111
  • You should be all set up
#!/bin/bash
awsmfa() {
~/.aws/mfa.sh $1 $2
source ~/.aws/token_file
echo "Your creds have been set in your env."
}
alias mfa=setToken
default="arn:aws:iam::123123123123:mfa/username"
#!/bin/bash
#
# Sample for getting temp session token from AWS STS
#
# aws --profile youriamuser sts get-session-token --duration 3600 \
# --serial-number arn:aws:iam::012345678901:mfa/user --token-code 012345
#
# Once the temp token is obtained, you'll need to feed the following environment
# variables to the aws-cli:
#
# export AWS_ACCESS_KEY_ID='KEY'
# export AWS_SECRET_ACCESS_KEY='SECRET'
# export AWS_SESSION_TOKEN='TOKEN'
AWS_CLI=`which aws`
if [ $? -ne 0 ]; then
echo "AWS CLI is not installed; exiting"
exit 1
fi
# 1 or 2 args ok
if [[ $# -ne 1 && $# -ne 2 ]]; then
echo "Usage: $0 <MFA_TOKEN_CODE> <AWS_CLI_PROFILE>"
echo "Where:"
echo " <MFA_TOKEN_CODE> = Code from virtual MFA device"
echo " <AWS_CLI_PROFILE> = aws-cli profile usually in $HOME/.aws/config"
exit 2
fi
#echo "Reading config..."
if [ ! -r ~/.aws/mfa.cfg ]; then
echo "No config found. Please create your mfa.cfg. See README.txt for more info."
exit 2
fi
AWS_CLI_PROFILE=${2:-default}
MFA_TOKEN_CODE=$1
ARN_OF_MFA=$(grep "^$AWS_CLI_PROFILE" ~/.aws/mfa.cfg | cut -d '=' -f2- | tr -d '"')
# echo "AWS-CLI Profile: $AWS_CLI_PROFILE"
# echo "MFA ARN: $ARN_OF_MFA"
# echo "MFA Token Code: $MFA_TOKEN_CODE"
#echo "Your Temporary Creds:"
aws --profile $AWS_CLI_PROFILE sts get-session-token --duration 129600 \
--serial-number $ARN_OF_MFA --token-code $MFA_TOKEN_CODE --output text \
| awk '{printf("export AWS_ACCESS_KEY_ID=\"%s\"\nexport AWS_SECRET_ACCESS_KEY=\"%s\"\nexport AWS_SESSION_TOKEN=\"%s\"\nexport AWS_SECURITY_TOKEN=\"%s\"\n",$2,$4,$5,$5)}' > ~/.aws/token_file
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment