Skip to content

Instantly share code, notes, and snippets.

@mankins
Created November 2, 2017 18:56
Show Gist options
  • Save mankins/505f2834bae53276bc2d9b39b5c51ffd to your computer and use it in GitHub Desktop.
Save mankins/505f2834bae53276bc2d9b39b5c51ffd to your computer and use it in GitHub Desktop.
aws mfa cli tool
#!/bin/bash
# From a user's MFA code, generate accesskey, secret, session token
#
# ENV inputs:
# AWS_CLI_INPUT = /path/to/token/config.json
# AWS_PROFILE = The Aws profile to use for aws commands
MFA_CODE=$1
if [ -z $MFA_CODE ]; then
echo "Usage: $0 MFA_CODE"
exit 1
fi
if [ -z "$AWS_CLI_INPUT"]; then
AWS_CLI_INPUT=~/.aws/generate_token_nonprod.json
fi
# generate .json with aws sts get-session-token --generate-cli-skeleton > ~/.aws/generate_token_nonprod.json
if [ ! -f $AWS_CLI_INPUT ]; then
echo "generate .json with aws sts get-session-token --generate-cli-skeleton > $AWS_CLI_INPUT"
exit 1
fi
AWS_CLI_INPUT=file://${AWS_CLI_INPUT}
if [ ! -z "$AWS_PROFILE" ]; then
TOKENS=`aws sts get-session-token --profile ${AWS_PROFILE} --cli-input-json ${AWS_CLI_INPUT} --token-code ${MFA_CODE} --output json | jq -r '.Credentials | "\(.AccessKeyId) \(.SecretAccessKey) \(.SessionToken)"'`
else
TOKENS=`aws sts get-session-token --cli-input-json ${AWS_CLI_INPUT} --token-code ${MFA_CODE} --output json | jq -r '.Credentials | "\(.AccessKeyId) \(.SecretAccessKey) \(.SessionToken)"'`
fi
read AWS_ACCESS_KEY_ID AWS_SECRET_ACCESS_KEY AWS_SESSION_TOKEN <<< ${TOKENS}
echo $AWS_ACCESS_KEY_ID $AWS_SECRET_ACCESS_KEY $AWS_SESSION_TOKEN
@mankins
Copy link
Author

mankins commented Nov 2, 2017

You could use in another script like this:

#!/bin/bash
echo -n "AWS MFA CODE? "
  read MFA_CODE

TOKENS=$(./aws-mfa.sh "$MFA_CODE")
read AWS_ACCESS_KEY_ID AWS_SECRET_ACCESS_KEY AWS_SESSION_TOKEN <<< ${TOKENS}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment