Skip to content

Instantly share code, notes, and snippets.

@jvacek
Forked from mankins/aws-mfa.sh
Last active September 7, 2021 14:16
Show Gist options
  • Save jvacek/9f2105b80af7f60f467b049c6dabdec2 to your computer and use it in GitHub Desktop.
Save jvacek/9f2105b80af7f60f467b049c6dabdec2 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}
export AWS_ACCESS_KEY_ID AWS_SECRET_ACCESS_KEY AWS_SESSION_TOKEN
echo $AWS_ACCESS_KEY_ID $AWS_SECRET_ACCESS_KEY $AWS_SESSION_TOKEN
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment